简体   繁体   English

Click事件不适用于jquery中动态更改的类

[英]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 我有两个类.btnn和.sleep_avail有时我会将.btnn的锚的css更改为.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. 现在,当我点击具有类sleep_avail的锚点时,它会从btnn类动态更改为btnn写入的事件,我会得到相应的响应。 But what i need is that the event for sleep_avail should be raised. 但我需要的是应该提出sleep_avail的事件。 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 因为事件处理程序绑定到当前元素,所以在.on()时它们必须存在于页面上

Here is the working DEMO http://jsfiddle.net/ARBdU/ 这是工作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 () {

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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