jQuery replaceWith()$ this

问题描述:

当我单击以显示它们时,我需要隐藏“显示答复”。问题是,当我点击“显示回复”时,所有“显示回复”按钮隐藏。我只需要隐藏那个我点击的那个。这是jQuery代码:

  $(".replies_show").click (function(e){ 
      $(".replies_show").replaceWith(" "); 
      $(this).next(".replies").show(); 
      e.preventDefault(); 
     }); 
+1

'$(this).hide()'? –

$(".replies_show")选择具有类的所有元素,因此你选择所有这些,然后再施加replaceWith到所有这些。但是,该回调函数内部的this指的是刚刚单击的元素(即只有单击的元素不是全部)。

此外,不要使用replaceWith函数只是为了隐藏一个元素,而是使用.hide()来代替。

所以,更换

$(".replies_show").replaceWith(" "); 

随着

$(this).hide(); 
+0

然后'$(this).next(“。回复”)。show();'不执行。回复没有显示 –

+0

@labasGamePagevisogero请看我编辑的答案。 –

+0

作品! 2分钟后我会接受 –

您可以使用this来获得当前元素。否则,您将选择.replies_show类的所有元素。

$('.replies_show').on('click', function(e, el) { 
 
    $(el).replaceWith(' '); // Does what you're looking for 
 

 
    $(el).hide(); // Might be better, depending on what you're doing 
 
    
 
    $(this).next('.replies').show(); 
 
    
 
    e.preventDefault(); 
 
});

使用.hide()功能不.replaceWith()

$(".replies_show").click (function(e){ 
      $(this).hide(); 
      $(this).next(".replies").show(); 
      e.preventDefault(); 
     }); 

,因为你需要只针对clicked项目,所以你需要在回调函数中使用$(this),类似如下:

$(".replies_show").click (function(e){ 
    var $this = $(this); // cache $(this)/clicked element 

    $this.hide();   // clicked item will be hide (display: none) 
    $this.next(".replies") // next matched item of clicked item 
     .show();   

    e.preventDefault(); 
});