我有以下代码:
<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"处理程序调用?
这个问题已经在jQuery中报告过了,并且已经用最新的代码库修复了。这是在jQuery 1.4 - 1.6.4中报告的。
当您将表单元素的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);
});
顺便说一下,您可能希望使用input
事件而不是change
。有一个jQuery插件:https://github.com/mathiasbynens/jquery.oninput.js