【坑】javascript中给元素加事件的方法名不要加小括号

来源:互联网 发布:python 网管snmp 编辑:程序博客网 时间:2024/05/18 03:14

有一天脑抽,傻傻的这样写了,我本来是想给一个按钮加一个输出文本框事件的。我是这样写的

<!doctype html><html><head><meta charset="utf-8"><title>无标题文档</title></head><body><input type="text" id="message"><input type="button" id="myButton"></body><script>window.onload = function(){var myButton = document.getElementById("myButton");var message = document.getElementById("message").value;myButton.onclick = sayHello(message);<span style="white-space:pre"></span>//易错点};function sayHello(str) {alert(str);}</script></html>

我在给button赋onclick事件的时候,方法名加了括号,这就相当于真的运行了那个sayHello方法,onclick赋的只是sayHello方法的返回值,正确的写法应该是这样的

<!doctype html><html><head><meta charset="utf-8"><title>无标题文档</title></head><body><input type="text" id="message"><input type="button" id="myButton"></body><script>window.onload = function(){var myButton = document.getElementById("myButton");myButton.onclick = sayHello;};function sayHello(e) {var str = document.getElementById("message").value;alert(str);}</script></html>

在onclick那里不要加括号,在sayHello中在获取输出的文本

0 0
原创粉丝点击