对于列表中包含带有文本的 span 的每个 li,从该 li 中删除另一个 span

For each li in list that contains span with text, remove another span from within that li

我有一个物品清单。 在每个列表项中,我都有跨度。 我想检查一个跨度是否包含一个字符串(在本例中为:"Account"),以仅从该列表项中删除另一个跨度。我按 Class 选择项目,而不是按 ID。

我试过这段代码:

$("ul").find('li .productRelatedToAdditional:contains("Account")').each(function(){
    if ($(".productRelatedToAdditional:contains('Account')").length > 0) {
       $(".productRelatedToAdditional").remove();
       $(".productRelatedTo").remove(); 
    }
});

但它不起作用。它正在从所有列表项中删除元素。 所以我只想从列表项中删除 Class "productRelatedTo" 和元素 "productRelatedToAdditional" 的范围,其中 class "productRelatedToAdditional" 的范围包含单词"Account"

非常感谢

$(document).ready(function(){
    $("li .productRelatedToAdditional:contains('Account')").each(function(){

    $(this).siblings(".productRelatedToAdditional, .productRelatedTo").remove(); 
});
});

http://jsfiddle.net/h9wj6bx7/2/

试试这个:找到 productRelatedToAdditional 的父 li 匹配,然后找到 productRelatedTo 并将其删除。

$("ul").find('li .productRelatedToAdditional:contains("Account")').each(function(){
       var $parentLi = $(this).closest('li');
       $(this).remove();
       $parentLi.find(".productRelatedTo").remove();
});

另请参阅工作代码片段

(function($) {
  $('li').each(function() {
    var string = $(this).find('.productRelatedToAdditional').html();
    console.log(string);
    if (string.toLowerCase().indexOf("active") >= 0) {
      $(this).find('.productRelatedTo').remove();
      $(this).find('.productRelatedToAdditional').remove();
    }
  });
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>

<body>
  <ul>
    <li>
      <span class="productRelatedTo">hello1</span>
      <span class="productRelatedToAdditional">active</span>
    </li>
    <li>
      <span class="productRelatedTo">hello2</span>
      <span class="productRelatedToAdditional"></span>
    </li>
    <li>
      <span class="productRelatedTo">hello3</span>
      <span class="productRelatedToAdditional">aCtiVe</span>
    </li>
    <li>
      <span class="productRelatedTo">hello4</span>
      <span class="productRelatedToAdditional"></span>
    </li>
  </ul>
</body>

</html>

这应该可以完成工作:

$('li').each(function(){
    var string = $(this).children('.productRelatedToAdditional').html();
    if (string.toLowerCase().indexOf("active") >= 0){
        $(this).children('.productRelatedTo').remove();
        $(this).children('.productRelatedToAdditional').remove();
    }
});

问候蒂莫修斯