第二个.click()函数不起作用

Uda*_*ora 8 jquery

第一个.click函数用于在容器中添加元素(div),第二个用于从容器中删除它.容器最初没有元素.通过单击删除该功能不起作用

$(document).ready(function(){
    $(".class1").click(function(){
       //Code for adding element to the container and 
       // removing class1 from it and adding class2

    });

    $(".class2").click(function(){
       alert("hi");   //Even the alert is not displayed
       $(this).fadeOut(100);    
    });
});
Run Code Online (Sandbox Code Playgroud)

但是,如果在页面加载容器之前元素已经存在,则它可以工作.有什么原因吗?是因为document.ready函数?解决方案?

Mat*_*att 17

那是因为当您为.class2元素添加单击处理程序时,您只是将事件添加到在该特定时刻具有该类的元素; 例如没有.

相反,你需要像这样使用事件委托;

$(document).on('click', '.class2', function () {
    alert('hi');
    $(this).fadeOut(100);
});
Run Code Online (Sandbox Code Playgroud)

这将起作用,因为它将事件绑定到document(始终存在),该.class2事件使用事件委派来侦听对任何元素的点击.有关详细信息,请阅读on()文档.