简体   繁体   中英

Click event is not working for dynamically changed class in jquery

I have two class .btnn and .sleep_avail sometimes i changes the css of a anchor from .btnn to .sleep_avail

Now i have two function for anchor click

 $('.btnn').click(function () {
     alert('yes btn');
 });

And Second one is

$('.sleep_avail').click(function () {
    alert('yes sleep');
});

Now when i click on the anchor with class sleep_avail which is changed dynamically from btnn class the event written for btnn raised and i get response accordingly. But what i need is that the event for sleep_avail should be raised. Kindly help.

Anytime, you use dynamically created tags, you must use

$(document).on('#event','#selector',function () {...});

so here

$(document).on('click','.sleep_avail',function () {...});

Because event handlers bind to the currently elements, they have to exist on the page when .on() is called

Here is the working DEMO http://jsfiddle.net/ARBdU/

$(document).on('click','.btnn, .sleep_avail',function () {  
 if($(this).hasClass('btnn'))
 {
    ...   
 }
 else if($(this).hasClass('sleep_avail'))
 {      
   ...
 }
});

尝试

$(document).on('click','.sleep_avail',function () {

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