选中第n个复选框时,是否定位某个类的第n个元素?

时间:2017-07-25 20:56:58

标签: javascript jquery html css checkbox

所以我有一组动态列出的元素,每个元素的结构如下:

<div class="under-item-description">
  <span class="under-compare-price">100</span><span class="under-price">50</span>
  <span class="under-compare-price-2">200</span><span class="under-price-2">100</span>
  <div class="under-quantity">
      <label class="under-quantity-button">
        <input type="radio" checked="checked" name="quantity-1" class="under-quantity-radio" value="1"/>
      </label>
      <label class="under-quantity-button">
        <input type="radio" name="quantity-2" class="under-quantity-radio" value="2"/>
      </label>
  </div>
</div>

.under-item-description div在页面上显示的次数可能会发生变化。目前,它显示了四次。

我想要做的是当用户在任何给定的.under-item-description div中点击第一个复选框(name =&#34; quantity-1&#34;)时, div。比较价格和.under-price显示,而.under-compare-price-2和.under-price-2隐藏。

如果单击第二个复选框(name =&#34; quantity-2&#34;),则显示.under-compare-price-2和.under-price-2,而.under-compare-price和.under-price只在那个 .under-item-description div。

中隐藏

这是我的JS:

$('.under-quantity-button').click(function(){
  $('.under-quantity-radio').each(function(){
    if($(this).is(':checked')){
        $('.under-compare-price:eq('+$(this).parents('.under-item-description').index()+'), .under-price:eq('+$(this).parents('.under-item-description').index()+')').show();
        $('.under-compare-price-2:eq('+$(this).parents('.under-item-description').index()+'), .under-price-2:eq('+$(this).parents('.under-item-description').index()+')').show();
    }
  });
});

然而,它似乎并没有像我想要的那样发挥作用。无论点击哪个第二个复选框,我都会在第一个和第三个元素上显示价格。当在任何地方点击第一个复选框时,它不会切换回来。有什么帮助吗?

1 个答案:

答案 0 :(得分:0)

围绕

中的每个选择单选按钮
<fieldset></fieldset>

这将允许它们独立工作,然后使用jQuery nearest()来选择要隐藏的元素。

https://api.jquery.com/closest/