开发者

What causes a jQuery event handler to silently fail? (Weird jQuery Behavior)

开发者 https://www.devze.com 2023-02-26 00:06 出处:网络
I am receiving unexpected behavior with a jQuery event handler.It is very similar to the problem discussed in this question: Why does my jQuery event handler fail when attached to multiple elements? .

I am receiving unexpected behavior with a jQuery event handler. It is very similar to the problem discussed in this question: Why does my jQuery event handler fail when attached to multiple elements? .

Basically, a simplified example is, my page calls

   $(document).ready(function(){
        $('a.submit').click(function(e){
              e.preventDefault();
              alert(this.href);
        });
   });

Assume the markup is:

<html>
    <body>
        <a href="url1" class="submit">text1</a>
        <a href="url2" class="submit">text2</a>
        <a href="url3" class="submit">text3</a>
    </body>
</html>

All of the links with the submit class except for the last one raise the event. The last link with .submit on the page does not get wired to the event handler. Replacing click(fn) with live('click',fn) works.

My problem is I don't understand why the original handler fails. All the links are rendered at the same time, and I am wr开发者_如何转开发apping my handler-subscription in a $(document).ready(), which should ensure the DOM is loaded.

I need to figure this out, because I have a more complex situation where the handlers are registered deep inside a minified javascript file, so it would be very helpful if I could understand how to prevent this bug instead of fixing it when it occurs.

One more thing to note is that I am receiving the same weird behavior in Firefox, Chrome and IE. I am using jQuery1.5.1


Considering the html you provided:

<a href="url1" class="submit">text1</a>
<a href="url2" class="submit">text2</a>
<a href="url3" class="submit">text3</a>

and JavaScript:

$(document).ready(function(){
        $('a.submit').click(function(e){
              e.preventDefault();
              alert(this.href);
        });
   });

it must work. no doubt about it. However, if your anchor tags <a> are being created dynamically, you can't bind the direct click event to those but through live such as

$('a.submit').on('click', function(e){
    //magic here
});
0

精彩评论

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