开发者

How to stop a second change event from firing in JQuery?

I'm having difficulty trying to work out a way I can update an input field without it in IE8 firing a second change event. In FF 3.6 this co开发者_StackOverflow中文版de work as I would want.

I thought returning false from the function event handler would stop any further events being fired but it doesn't appear so in IE.

Here's what I have tried so far:

  1. Returning false in a live event handler.
  2. Used bind and event.stopImmediatePropagation(). Although I would like to use live in the real code I'm using as form elements are being swapped in/out via AJAX calls.
  3. Used die and live again before and after the input field update. But I guess this update to the input field occurs after the function has finished.

Is there something obvious I'm missing here? I'm fairly new to JQuery so maybe I've made a silly error :)

Thanks!

Here's some test code to show the problem:

    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>

    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>

    <script>

    var counter = 0;

     $(document).ready(function() {


        $('.eventHandler').live('change', handleChangeEvent);

        });

    function handleChangeEvent(event){

        //$('.eventHandler').die();

        $(this).val(counter++);

        //$('.eventHandler').live('change', handleChangeEvent);

        return false;

    }

    </script>

    </head>
        <body>
            <form>
                <input type="text" value="0.00" id="54501" class="eventHandler"/>
            </form>
        </body>
    </html>

Answered my own problem

Not allowed as a new user to answer my own question for 8 hrs. So will put here for now

Just figured it by explaining the problem more to Dr.Molle. Always the way helps to talk a problem through.

Because the input still had focus when I updated the input field value, when I clicked away it triggers another 'change' event.

So if I remove the focus before updating the input field value it never triggers another event.

I changed the code to this and works as I wanted it to in IE:

    var counter = 0;

     $(document).ready(function() {


        $('.eventHandler').unbind('blur').live('change', handleChangeEvent);

        });

    function handleChangeEvent(event){


        $('body').focus();


        $(this).val(counter++);
        event.preventDefault();




        return false;

    }

Thanks for your help Dr.Molle, in explaining it more it helped me work it out - Cheers!!!


You may first unbind the already bound change-events:
$('.eventHandler').unbind('change').live('change', handleChangeEvent);

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜