Home > Article > Web Front-end > Why is the event bound by jquery using click invalid?
jqueryEvent bound using clickInvalid
$(this).children(":last").prev().after("<div class='bounty-add'><a target='_blank' href='bounties.php#/p=add&XID=" + playerId + "'>[Bounty]</a></div>"); $(this).children(":last").prev().after("<div class='info-add'><a href='#'>[Refresh]</a></div>"); $("div.bounty-add").css(addStyle); $("div.info-add").css(addStyle); $(this).children(":last").prev().children("a").click(function() { alert("Hello"); });
The relevant basic code is as above, the Refresh a element can be obtained smoothly, but it is the bound click event Invalid, no valid binding can be found in the "Event Listeners" of "Elements" in Chrome's "Developer Tools".
The DOM added by the basic code above is all valid. The outer layer is two each loops, but I feel that it should have no impact. All codes can be executed smoothly, including the binding step. Even if you click on the a element after the execution is completed, it will not work, and you can't find the function bound to it. . . . . . .
$(this).children(":last").prev().children("a").on("click",function() { alert("Hello"); });
on I also tried it, but it didn’t work. It seems that these two are basically the same?
Because the a element itself has the clickable attribute, after clicking, it will still respond to its original event, such as href=‘#’, and a # will be added at the end of the address bar. . . . I wonder if it is because the original event overwrites the later added event? . . . . .
Your previous binding was
$(this).children(":last").prev().children("a").on("click",function() { alert("Hello"); });
The same as normal click binding
Try binding like this
$(this).on("click",".info-add a",function() { alert("Hello"); });
Your element is dynamically generated ?
If so, use live or delegate binding
live jquery1.9 has removed it. Now it is not that the element cannot be found or cannot be bound, but that it is invalid after binding.
I directly changed a to p element, which is also included in click listeners, but the alter("hello"); cannot be triggered no matter what. . . . . .
First, use firebug to see if there is a script error on the page
Again, make sure your code finds the a element
Finally. You can use
$(document).on("click",".info-add",function(){ alert("ok") })
If that doesn’t work, please send me the complete code
The above is the detailed content of Why is the event bound by jquery using click invalid?. For more information, please follow other related articles on the PHP Chinese website!