为什么这个jQuery事件运行两次?
Why does this jQuery event run twice?
当您运行此代码并单击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>
这是一个已知的jquery bug:
http://bugs.jquery.com/ticket/6705IE错误调用focus
两次
更新:修复…从focus切换到focusin,删除了input2中无法获得focus的错误。
这似乎是Internet Explorer独有的问题。添加一个对preventDefault的调用来修复双焦点问题。这是一个为我工作的jsFiddle。
<!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>
虽然它似乎不被复制,但我已经看到当多个事件绑定到控件时发生这种问题。当您绑定了focus()事件两次时,就会发生这种情况。这可能值得探索,并在代码之前清除现有的绑定。
相关文章:
- Append元素在运行两次函数后不显示
- 我的所有代码在使用Webpack编译时都会运行两次
- 为什么两次运行完全相同的正则表达式的结果不同
- JavaScript/JQuery表单验证运行两次
- 若在两个不同的选项卡中打开同一个页面,如何防止javascript运行两次
- jQuery停止函数运行两次
- Socket.IO:重新连接导致服务器连接代码运行两次
- Gulp任务似乎运行了两次,而不是一次
- 函数jQuery.animation()运行了两次行,但不起作用
- nodejs - 为什么我的异步函数运行两次
- 模板函数在加载网页时运行两次
- 为什么 document.onreadystatechange 运行两次
- 我需要运行此功能两次
- 为什么 ajax 'application/json' 要运行 PHP 代码两次
- 必须在 Firefox 中运行两次 removeChild()
- nodeJs,运行两次sql可以将它们组合成json
- 防止脚本在执行时运行两次
- D3.js键功能在简单的选择器/数组组合上运行两次
- JS运行两次不起作用
- 如何防止 iframe 运行两次加载事件