javascript - 单击按钮会触发 window.onfocus 而不是 button.onclick

标签 javascript jquery

更新:这只在我们调试时发生

我的代码如下所示:

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 函数中放置了一个警报。焦点事件将首先触发,并显示警报。然后您需要单击“确定”才能关闭该警报。然后按钮单击事件将不会触发。

Fiddle with alert

如果您将 console.log 放入该函数中,不需要任何用户输入,则按钮单击事件将触发。

Fiddle with 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/

相关文章:

javascript - Discord.Js Bot 为用户创建邀请

javascript - jQuery 克隆和绑定(bind)事件问题

javascript - 如何将 Jhtmlarea 编辑器设置为空白或为空

javascript - 拖放以弹出添加预填充的新模态表单?

javascript - 一个网页一次只打开1个分区的脚本

javascript - 将多边形合并到 Google Maps API 3 中

javascript - 像 iframe 和 jquery 一样使用 div

javascript - Ember 2.0 中离开路线时提醒用户

javascript - knockout js插入额外的空元素

javascript - 谷歌标签管理器 : How to use "Custom Javascript" in a "Custom HTML Tag?"