【问题标题】:Targeting the nth element of certain class when nth checkbox is checked?选中第 n 个复选框时定位某个类的第 n 个元素?
【发布时间】:2017-12-31 23:21:02
【问题描述】:

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

<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") 时,that 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();
    }
  });
});

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

【问题讨论】:

  • 你让这种方式比它需要的更复杂。使用.parents() 向上到.under-item-description 祖先元素,然后简单地.find() 那里所需的后代。
  • @CBroe 试过了。它似乎仍然针对 .under-item-description 的每个类,而不仅仅是其父级的子级。
  • 你还在做$('.under-quantity-radio').each的事情吗?那么有了那个,你也必须更具体地选择你的选择。同样,find 是一种仅在给定父级的子树中进行选择的简单方法。

标签: javascript jquery html css checkbox


【解决方案1】:

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

<fieldset></fieldset>

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

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

【讨论】:

    猜你喜欢
    • 2021-10-03
    • 2019-09-16
    • 2015-06-05
    • 2012-07-09
    • 1970-01-01
    • 1970-01-01
    • 2014-01-20
    • 2023-03-19
    • 1970-01-01
    相关资源
    最近更新 更多