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”处理程序调用?
I have the following code:
<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>
In IE8 if i enter any text to "test" input and press "Tab" I'll get alert message twice.
But if I comment line "this.value = jQuery.trim(this.value);" the message will be shown only once.
Why this happened? And how I can avoid twice "onchange" handler invoking?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题已在 jQuery 中报告,并已使用最新的代码库修复。
这是在 jQuery 1.4 - 1.6.4 上报道的。
The Issue has been reported in jQuery and it has been fixed with the latest code base.
That was reported on jQuery 1.4 - 1.6.4.
当您将表单元素的
value
属性设置为不同的值时,将触发change
事件。因此,在您的代码中:
顺便说一下,您可能想使用
input
事件 而不是更改
。有一个 jQuery 插件: https://github.com/mathiasbynens/jquery.oninput.js< /a>When you set the
value
property of a form element to a different value, thechange
event fires.So, in your code:
By the way, you probably want to use the
input
event instead ofchange
. There’s a jQuery plugin for that: https://github.com/mathiasbynens/jquery.oninput.js