Javascript 为什么这个jQuery事件运行两次?
当您运行此代码并单击Javascript 为什么这个jQuery事件运行两次?,javascript,jquery,events,Javascript,Jquery,Events,当您运行此代码并单击input2时,它将获得焦点并。resultdiv将输出“f2”一次。但是当您单击input1时,脚本将让input2获得焦点并。resultdiv将输出“f2”两次,为什么 <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>blank</title
input2
时,它将获得焦点并。result
div将输出“f2”
一次。但是当您单击input1
时,脚本将让input2
获得焦点并。result
div将输出“f2”
两次,为什么
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>blank</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".input1").click(function(){$(".input2").focus();});
$(".input2").focus(function(){$(".result").html($(".result").html()+"f2, ");});
});
</script>
</head>
<body>
<p>
<input class="input1" value="click me to set the input2's focus" />
<input class="input2" value="input2" />
<div class="result"></div>
</p>
</body>
</html>
空白的
$(文档).ready(函数(){
$(“.input1”)。单击(函数(){$(“.input2”).focus();});
$(“.input2”).focus(函数(){$(“.result”).html($(“.result”).html()+“f2,”;});
});
虽然它似乎没有被复制,但我看到当多个事件绑定到控件时会出现这种问题。这可能发生在绑定focus()事件两次之后。这可能值得探索,并在编写代码之前清除现有绑定。这是一个已知的jquery错误:
IE错误地调用
焦点两次。更新:修复。。。从focus切换到focusin删除input2中的未获得焦点错误
这似乎只是Internet Explorer的问题。添加对preventDefault的调用以修复双焦点问题
空白
$(文档).ready(函数(){
$(“.input1”)。单击(函数(){$(“.input2”).focus();});
$(“.input2”).focusin(函数(e)
{
e、 预防默认值();
$(“.result”).html($(“.result”).html()+“f2”);
});
对我来说,这是正确的:@Pointy:(比我快:P)哦,它在Internet Explorer中无法正常工作!明白了。IE中错误调用了两次焦点。是的,但它也阻止了.input2实际聚焦。:/但是当我添加preventDefault时,input2无法获得焦点。哈,我根本没有注意到这一点。我在JSFIDLE中也使用了相同的解决方案,并且注意到了ju在我开始把它发布到这里之前:)Add preventDefault方法等于添加一个“return false”。在这种情况下,这是IE中的一个明显错误,如在IE中运行JSFIDLE示例所示
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>blank</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".input1").click(function(){$(".input2").focus();});
$(".input2").focusin(function(e)
{
e.preventDefault();
$(".result").html($(".result").html()+"f2, ");
});
</script>
</head>
<body>
<p>
<input class="input1" value="click me to set the input2's focus" />
<input class="input2" value="input2" />
<div class="result"></div>
</p>
</body>
</html>