Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/meteor/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript jQuery单击事件删除第一个元素_Javascript_Jquery - Fatal编程技术网

Javascript jQuery单击事件删除第一个元素

Javascript jQuery单击事件删除第一个元素,javascript,jquery,Javascript,Jquery,我正在处理一个项目和我的.ejs文件,我有一个弹出窗口: <div id="just-claimed-popup2" class="popup"> <h6>You just claimed:</h6> <h2 id="card-just-claimed"></h2> <p class="show-message">Show this Screen!</p> <button id="d

我正在处理一个项目和我的.ejs文件,我有一个弹出窗口:

<div id="just-claimed-popup2" class="popup">
   <h6>You just claimed:</h6>
   <h2 id="card-just-claimed"></h2>
   <p class="show-message">Show this Screen!</p>
   <button id="deletePromoFromHome" class="close-button">Close</button>
</div>

问题:它总是只删除单击的第一张卡,如果您单击另一张卡上的按钮,它将停止工作,因此它只工作一次。如果I console.log发生了单击事件,那么它只是没有运行其中的代码。

尝试将处理程序更改为:

$('body').on('click', `#promotion-container .promo${i} .redddButt`, function(e){
  //function stuff here
}

问题可能是元素是在附加处理程序之后生成的

您的代码缺少一些结束标记。由于卡是动态生成的,请尝试使用未测试:

var buttonContext;

$(document).on('click', '#promotion-container .promo .redddButt', function() {
     buttonContext = $(this);
    // Something 
});

$('#deletePromoFromHome').click(function(){
    buttonContext.closest('.promo').fadeOut("slow");
});
您可以省略这一行:$div.promo${i}.addClass'toDelete'

这些卡片可能只有一个类.promo而不是.promo,除非你想做进一步的操作,比如说不同的样式等等


有关$document:

的更多详细信息,请选中此项,而不是在循环中添加单独的事件处理程序,而是对具有相同类的所有元素使用事件委派。然后使用相对于$this的DOM导航在他们单击的同一张卡上进行操作。不能有多个元素具有任何给定的id值。改用CSS类。我试着用$this.fadeOut'slow'或$this.addClass'toDelete'来做,但它把它添加到了错误的位置。我是否需要向循环中添加其他内容?对不起,我还是新来的,有$this的好小费!我把所有的东西都改成了类,但它仍然只工作一次我是什么??您是否正在循环某些内容,并将上述所有代码都包含在循环中?谢谢您的建议!但是,它仍然只删除了第一个:在处理程序中尝试$$this.parents[3].addClass'toDelete'。但是要小心,这种方法几乎不依赖于html标记。另外,不确定索引。
$('body').on('click', `#promotion-container .promo${i} .redddButt`, function(e){
  //function stuff here
}
var buttonContext;

$(document).on('click', '#promotion-container .promo .redddButt', function() {
     buttonContext = $(this);
    // Something 
});

$('#deletePromoFromHome').click(function(){
    buttonContext.closest('.promo').fadeOut("slow");
});