简体   繁体   中英

Why Jquery on click event not getting triggered?

I have an group of checkboxes with id's starting with somename and i want catch the click event of these checkboxes. Previously i have done this through jquery. ie $("input[id^='somename']").click(function(){ // my code follows here }) but this is not working this time around. why?

PS The element is created via javascript after the page is fully loaded after making some ajax request. i don't know if this may be the problem?

just use live if elements are created after the page is loaded.

$("input[id^='somename']").live('click', function(){ // my code follows here })

PS : Your search selector is "somename" but you search it on the attribute ID, are you sure that you don't want :

$("input[name^='somename']").live('click', function(){ // my code follows here })

instead?

This indeed could be the problem. Replace .click with .live()

$("input[id^='somename']").live('click', function(){ // my code follows here })

and you should be fine.
Since a call to .click is just a shortcut for .bind('click', fnc) , this will not work if the element is not in the DOM when calling this. Even better than using .live() would be to use .delegate() . Have a read:

.live() , .delegate()

Using the standard binding functions only works on elements that exist at the time of the bind. You need to use something called event delegation, where elements further up the DOM tree are notified of events on descendant elements. The best way to do this is with .delegate() :

$('#containingElement').delegate("input[id^='somename']", 'click', function(){
    // your code here
});

This assumes that you have an element #containingElement that contains all the elements that you want to capture the events on.

NB that other answers recomment live . live and delegate use the same backend code, but for various reasons delegate is more efficient.

I believe that because you want this applied to dynamically created elements in the DOM you are going to have to use the the jQuery . live() method:

$("input[id^='somename']").live('click', function(e) {
     // Your code
});

相反的.click()尝试.change()事件。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM