我遇到了这个问题,当处理程序作为内联函数调用提供时,JavaScript 事件处理程序会按预期被调用,但是当调用另一个函数来响应事件时,它不会按预期工作。我不确定为什么会这样,如果有人能解释一下那就太好了。谢谢。
<html>
<head>
</head>
<body>
Name: <input type="text" id="text1"> Hello World!
<script>
var i= 0;
function myFun()
{
i++;
console.log('got key up event ' + i);
}
var textElem = document.getElementById('text1');
//below works as expected ie. prints 'got key up event 1', 'got key up
event 2' .. on console
//textElem.addEventListener('keyup', function () {i++; console.log('got key up event ' + i);});
//If we comment above call and use below - textElem.addEventListener...
// it does not work as expected it only logs 'got key up event 1' on page load
// after that it (myFun) is not getting called even if i press key on text box.
//textElem.addEventListener('keyup', myFun() );
</script>
</body>
</html>
最佳答案
尝试:
textElem.addEventListener('keyup', myFun );
即myFun
没有 ()
addEventListener
需要一个函数作为第二个参数。如果您传递 myFun()
,浏览器会评估该函数(这里您得到 got key up event 1
),但该函数不会返回任何内容,因此实际的事件监听器不是添加。
当您传递myFun
时,实际函数将被添加为事件监听器。
关于javascript - Javascript 事件处理程序未按预期触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29577096/