2012-06-22 88 views
6

第一个.click函数用于在容器中添加元素(div),第二个用于将其从容器中移除。该容器最初没有元素。通过点击删除功能是行不通的第二个.click()函数不起作用

$(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);  
    }); 
}); 

但是,它的工作原理,如果在页面加载到容器之前,元素已经存在。 任何原因为什么?是否因为document.ready函数?解决方案?

+3

给我们您的HTML请。 –

+0

请发布html – Sudantha

+0

当您将事件添加到'.class2'元素时,您的元素是否已经存在? –

回答

14

这是因为,当你添加点击处理程序.class2元素,你只需要添加该事件,其中有一个类元素在该特定时刻;例如没有。

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

$(document).on('click', '.class2', function() { 
    alert('hi'); 
    $(this).fadeOut(100); 
}); 

,因为它结合于document一个事件(其总是存在),该监听使用事件代理任何.class2元素的点击次数这将工作。欲了解更多信息,请阅读on()文档。

+0

chrome block this script –

+0

@mohsen:我会仔细检查一下。代码并不少见。 Chrome会阻止它非常奇怪。 – Matt

+0

我使用.on函数来动态更改超链接链接,但chrome阻止了我在超链接上的第二次更改。 (顺便说一下,超链接包含(java:win.open ....)但在第一个链接没有问题,第二个动态改变。被所有浏览器阻止) –

1

当您尝试添加代码点击.class2它尚未创建,因为我明白。 尝试添加点击事件,您所创建的.class2元素像这样经过:

$(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); 

     }); 
    }); 
}); 
+0

这将为现有的'.class2'元素添加一个事件处理程序。 – Matt

+0

是的,你是对的。你的答案是正确的。谢谢:我不知道在jquery中的代表团! – devsnd

3

对两个类都使用委托事件处理程序(如果您在两者之间切换,或者如果您不回到class1那么第二个就足够了),因为在更改class后,元素被视为动态。

$("#container").on("click", ".class1", function(){ 

}); 

$("#container").on("click", ".class2", function(){ 

}); 

这里#container指的是那些类的父亲,你可能有别的东西。

0

当函数被详细阐述时,不能将事件转换为不存在的元素。但是,你可以创建一个包装元素(DIV)围绕“1类”和“类2”,像这样:

<div id="class1_wrapper"> 
    <span class="class1"> 
</div> 

我用“跨度”类class1,因为我不知道它是哪个元素。然后,而不是点击事件,您可以使用“上()”:

$("#class1_wrapper").on("click", ".class1", function() 
{ 
    //Code for adding element to the container and removing class1 from it and adding class2 
}); 

这样一来,即使class1的是不存在的(同样可以为Class2中完成),单击事件将运行

+0

感谢马特纠正我的错字:) –