如何在clicked元素上添加类,但是通过nearest()方法从其他元素中删除

时间:2015-12-04 11:16:17

标签: javascript jquery html

如何在单击.line类时将.active类更接近.table-cell-right类,但同时通过在jquery中使用nearest()方法从所有其他位置删除.active类。

   <div class="line">
     <div class="table-cell">
       <span class="zky-points">1 ZKY </span><span class="sp-symbol">℗</span>
     </div>
     <div class="table-cell-right">
       <span class="euro">€</span> 1ZKY
       <button name="credit" class="btn btn-primary buy-credit" type="button">Buy Credit<div class="ripple-wrapper"></div></button>
     </div>
    </div>

    <div class="line">
     <div class="table-cell">
       <span class="zky-points">1 ZKY </span><span class="sp-symbol">℗</span>
     </div>
     <div class="table-cell-right">
       <span class="euro">€</span> 1ZKY
       <button name="credit" class="btn btn-primary buy-credit" type="button">Buy Credit<div class="ripple-wrapper"></div></button>
     </div>
    </div>

1 个答案:

答案 0 :(得分:1)

需要closest功能。因为您没有更改父级,而是更改子元素。所以你需要有效地使用find()

$(".line").click(function () {
    // Remove all the other classes.
    $('.active').removeClass('active');
    // Add the correct active class.
    $(this).find('.table-cell').addClass('active');
});