Jquery 第二个.click()函数不起作用
第一个.click函数用于在容器中添加元素(div),第二个用于将其从容器中删除。容器最初没有元素。通过单击该函数来删除该函数不起作用Jquery 第二个.click()函数不起作用,jquery,Jquery,第一个.click函数用于在容器中添加元素(div),第二个用于将其从容器中删除。容器最初没有元素。通过单击该函数来删除该函数不起作用 $(document).ready(function(){ $(".class1").click(function(){ //Code for adding element to the container and // removing class1 from it and adding 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);
});
});
但是,如果在页面加载到容器中之前元素已经存在,那么它就可以工作。
有什么原因吗?是因为document.ready函数吗?解决方案?当您尝试添加代码以单击
。class2
时,据我所知,它尚未创建。
创建.class2
元素后,尝试添加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);
});
});
});
<div id="class1_wrapper">
<span class="class1">
</div>
这是因为当您为
.class2
元素添加click处理程序时,您只会将事件添加到在特定时刻具有该类的元素中;e、 g没有
相反,您需要像这样使用事件委托
$(document).on('click', '.class2', function () {
alert('hi');
$(this).fadeOut(100);
});
这将在它将事件绑定到
文档
(始终存在)时起作用,该文档使用事件委派侦听对任何.class2
元素的单击。有关更多信息,请阅读文档。对这两个类使用委托事件处理程序(如果您在这两个类之间切换,或者如果您没有返回到class1
,则第二个就足够了),因为在更改类之后,元素被视为动态的
$("#container").on("click", ".class1", function(){
});
$("#container").on("click", ".class2", function(){
});
在这里,#container
指的是这些类的父类,您可能还有其他内容。在详细说明函数时,不能对不存在的元素强制转换事件。但是,您可以围绕“class1”和“class2”创建一个包装器元素(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);
});
});
});
<div id="class1_wrapper">
<span class="class1">
</div>
这样,即使class1不存在(对class2也可以这样做),当您将事件添加到.class2
元素时,单击事件将运行。您的元素是否已经存在?添加该元素后,您需要将事件处理程序设置到元素。这也会将事件处理程序添加到现有的.class2
元素。是,你是对的。你的答案是正确的。谢谢:我不知道jquery中的委托!铬块script@mohsen:我会再检查一遍。代码并不罕见。Chrome阻止它会非常奇怪。我使用.on函数动态更改超链接,但Chrome阻止了我对超链接的第二次更改。(顺便说一句,超级链接包含(java:win.open…)但第一个链接没有问题,第二个链接动态更改为.on被所有浏览器阻止)我没有被Chrome阻止。