jQuery onchange 事件在 IE8 中触发两次

发布于 2024-11-28 23:28:40 字数 792 浏览 7 评论 0原文

我有以下代码:

<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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

z祗昰~ 2024-12-05 23:28:40

问题已在 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.

手心的温暖 2024-12-05 23:28:40

当您将表单元素的 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 事件 而不是更改。有一个 jQuery 插件: https://github.com/mathiasbynens/jquery.oninput.js< /a>

When you set the value property of a form element to a different value, the change event fires.

So, in your code:

$('#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);
});

By the way, you probably want to use the input event instead of change. There’s a jQuery plugin for that: https://github.com/mathiasbynens/jquery.oninput.js

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文