2017-07-25 42 views
1

所以我有一个动态列出组元件,每个结构如下:当选中第n个复选框时,定位某个类的第n个元素?

<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项-描述的div在网页上显示的次量可以改变。目前,它显示四次。

我想要做的是当用户点击任何给定的.under-item-description div中的第一个复选框(name =“quantity-1”)时, div的.under-compare-price和。低价表示,而低于价格-2和低价-2隐藏。

如果点击第二个复选框(名称=“quantity-2”),则会显示.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

您正在使这种方式比它需要更复杂。使用'.parents()'进入''.under-item-description'祖先元素,然后简单地'.find()'在那里所需的后代。 – CBroe

+0

@CBroe试过。它似乎仍然是针对每一类.under-item-description,而不仅仅是其父母的子女。 – AKor

+0

你还在做'$('。under-quantity-radio')。那么在那个人中,你必须在你的选择中更具体。同样,'find'也是一种简单的方法,只能在给定父代的子树中进行选择。 – CBroe

回答