javascript - 当选中第 n 个复选框时,针对某个类的第 n 个元素?

标签 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="quantity-1") 时, div 的 .under- Compare-price 和 .under-price 显示,而 .under-compare-price-2 和 .under-price-2 隐藏。

如果单击第二个复选框 (name="quantity-2"),则会显示 .under-compare-price-2 和 .under-price-2,同时显示 .under-compare-price 和 .under-price隐藏,仅在 that .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();
    }
  });
});

但是,它似乎没有按照我想要的方式运行。无论单击第二个复选框,价格都会显示在第一个和第三个元素上。当在任何地方单击第一个复选框时,它不会切换回来。有什么帮助吗?

最佳答案

将每个单选按钮的选择包围在

<fieldset></fieldset>

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

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

关于javascript - 当选中第 n 个复选框时,针对某个类的第 n 个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45313344/

相关文章:

javascript - 使用 jQuery 或 javascript 检查数字子集是在系列的开始部分还是系列的底部

javascript - 为什么 document.getElementById 在页面中获取多个 iframe 时返回 null

jquery - 带有Google事件跟踪的jQuery中的变量

jquery 和字体大小

html - <h1>、<h2>、<h3>... 标签,在段落内内联 (<p>)

javascript - 在 JS 中更改鼠标悬停时文本的颜色

javascript - 插入后按钮未绑定(bind) jQuery 类

javascript - 如何使用 jQuery 将多个 GET 放入一个数组中

javascript - 如何将 localstorage 的值从 View 传递到 Controller 以用作另一个 View 中的 php 变量

html - CSS - 绝对内固定,滚动溢出和 100% 高度