首页 > 解决方案 > 当关联元素包含字符串时,jQuery 仅隐藏下一个元素的最佳方法

问题描述

我有一个案例,我想根据另一个元素(“test”)的文本值隐藏一个元素(“target”)。当我找到元素(“测试”)时,我有代码隐藏元素(“目标”)的所有情况,但我只想隐藏下一个元素(“目标”)继续对其他“测试”元素的操作。

示例 html:

<div class="cart-item-block cart-item-option-list">
  <div class="cart-item-option">
    <span class="cart-item-option-name">
   Select card type:
  </span>

  <span class="cart-item-option-value">
    Standard Card
  </span>
  </div>
  <div class="cart-item-option">
      <span class="cart-item-option-name">
       Add a personal message ($2 extra for Standard cards):
  </span>

  <span class="cart-item-option-value">
    No
  </span>
  </div>
</div>

<div class="cart-item-block cart-item-giftwrap">
  <div class="giftwrap-item">
   <a class="giftwrap-item-add" href="#" data-item-giftwrap="d55d1fd6-1ad6-4766-a769-0843e950008e" data-text-short="Add" data-text-long="Add Personal Message">
    <svg role="presentation"><use xlink:href="#icon-increment-regular"></use></svg>
  </a>
 </div>
</div>

<div class="cart-item-block cart-item-option-list">
<div class="cart-item-option">
  <span class="cart-item-option-name">
   Select card type:
  </span>

  <span class="cart-item-option-value">
    Standard Card
  </span>
</div>
<div class="cart-item-option">
  <span class="cart-item-option-name">
    Add a personal message ($2 extra for Standard cards):
  </span>

  <span class="cart-item-option-value">
    Yes
  </span>
 </div>
</div>

<div class="cart-item-block cart-item-giftwrap">
 <div class="giftwrap-item">
  <a class="giftwrap-item-add" href="#" data-item-giftwrap="d55d1fd6-1ad6-4766-a769-0843e950008e" data-text-short="Add" data-text-long="Add Personal Message">
    <svg role="presentation"><use xlink:href="#icon-increment-regular"></use></svg>
  </a>
 </div>
</div>

class="cart-item-option-value" 为 Yes 的情况也是如此,我们显示 class="giftwrap-item" 并在 class="cart-item-option-value" 为 No 时隐藏 ..

这是我当前的 jQuery - 它设法隐藏 ALL class="giftwrap-item" .. FML

//jquery to hide giftwrap option in the cart when The value of Add a personal message is No
$(location).attr('href');
if(window.location.href.indexOf("cart") > -1) {
    var x = $('.cart-item-option-value').text();
    var theTest = 'No';

    if(x.indexOf(theTest) != -1){
            $('.giftwrap-item-add').hide();
       alert( x );
           }
}

标签: jquery

解决方案


我采用的解决方案如下..

$(location).attr('href');
if(window.location.href.indexOf("cart") > -1) {
   $(".cart-item-option-value:contains('No')").parent().parent().next().hide();
}

推荐阅读