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

时间:2015-06-18 12:13:47

标签: javascript jquery

UPDATE:这只在我们调试时发生

我的代码如下所示:

function onFocus(){
    //do something
}
window.onfocus = onFocus;
//do other things
$('#button1').unbind().bind("click",function(){
    alert('button1 clicked');
});

当我单击按钮时,onFocus代码会执行,但是按钮1单击永远不会执行。为什么会发生这种情况并且有解决方法?

编辑: 完整的测试页面:

<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>

3 个答案:

答案 0 :(得分:2)

可能的原因是,您可能在onFocus函数中放置了警报。焦点事件将首先触发,将显示警报。然后,您需要单击ok才能关闭该警报。然后按钮点击事件将不会触发。

Fiddle with alert

如果你在一个不需要任何用户输入的函数中放入一个console.log,那么按钮点击事件将会触发。

Fiddle with console.log

在注释中粘贴的代码不会正确绑定click事件。您需要将其包装在document.ready

function onFocus() {
    console.log("onfocus triggered");
}
window.onfocus = onFocus;
//do other things
$(document).ready(function () {
    $('#button1').click(function () {
        console.log("button1 clicked");
    });
});

答案 1 :(得分:0)

简单地这样做:

$('#button1').click(function(){
    alert('button1 clicked');
})

答案 2 :(得分:0)

也许它不喜欢你没有<body>标签的事实?