更新:这只在我们调试时发生
我的代码如下所示:
function onFocus(){
//do something
}
window.onfocus = onFocus;
//do other things
$('#button1').unbind().bind("click",function(){
alert('button1 clicked');
});
当我单击按钮时,onFocus 代码会执行,但单击的button1 永远不会执行。为什么会发生这种情况?有解决方法吗?
编辑: 完整测试页面:
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
function onFocus(){
console.log("onfocus triggered");
}
window.onfocus = onFocus;
//do other things
$('#button1').unbind().bind("click",function(){
console.log("button1 clicked");
});
</script>
<input type="button" id="button1">Test</input>
</html>
最佳答案
可能的原因是,您可能在 onFocus
函数中放置了一个警报。焦点事件将首先触发,并显示警报。然后您需要单击“确定”才能关闭该警报。然后按钮单击事件将不会触发。
如果您将 console.log 放入该函数中,不需要任何用户输入,则按钮单击事件将触发。
您在注释中粘贴的代码将无法正确绑定(bind)点击事件。您需要将其包装在 document.ready
中。
function onFocus() {
console.log("onfocus triggered");
}
window.onfocus = onFocus;
//do other things
$(document).ready(function () {
$('#button1').click(function () {
console.log("button1 clicked");
});
});
关于javascript - 单击按钮会触发 window.onfocus 而不是 button.onclick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30915052/