2011-08-10 46 views
1

我有以下代码:jQuery的onchange事件触发两次在IE8

<html> 
<head> 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js" type="text/javascript"></script> 
</head> 
<body> 

    <script type="text/javascript"> 

     $(document).ready(function() 
     { 
      $('#test').bind("change", function() 
      { 
       alert(this.value); 
       this.value = jQuery.trim(this.value); 
      }); 
     }); 

    </script> 

    <input type="text" id="test" /> 
    <br /> 
    <input type="radio" /> 
</body> 
</html> 

在IE8中,如果我输入任何文字,以“测试”输入,按“TAB”我会得到警告信息两次。

但是,如果我注释行 “THIS.VALUE = jQuery.trim(THIS.VALUE);”该消息将只显示一次。

为什么发生这种情况?以及如何避免两次“onchange”处理程序调用?

回答

2

当您将表单元素的value属性设置为不同的值时,将触发change事件。

所以,在你的代码:

$('#test').change(function() { 
    // This is executed whenever the `change` event fires 
    // Setting a new value will trigger the `change` event again 
    this.value = $.trim(this.value); 
}); 

顺便说一句,你可能想使用the input event,而不是change。这里有一个jQuery插件:https://github.com/mathiasbynens/jquery.oninput.js

+0

但在Chrome 13中,FF4 onchange事件仅触发一次。 – maxvasil

+2

@vasmt这是跨浏览器脚本的亚! –

3

Issue已经在jQuery中报告过,并且已经使用最新的代码库修复了它。 这是在jQuery 1.4 - 1.6.4上报告的。