2017-01-16 27 views
0

我想單擊a.bc-pagination-next時顯示元素li.bc-cate-has-child.first,並在點擊a.bc-pagination-next時將其隱藏。只需點擊父容器中的元素

下面的腳本工作,但點擊將顯示/隱藏兩個容器中的所有匹配元素,我如何保持點擊只是影響父容器中的元素?

腳本:

$(document).ready(function() { 
    $('.bc-list-wrap').each(function() { 
     $("a.bc-pagination-next").click(function() { 
      $("li.bc-cate-has-child.first").hide(); 
     }) 

     $("a.bc-pagination-prev").click(function() { 
      $("li.bc-cate-has-child.first").show(); 
     }) 
    }); 
}); 

HTML:

<div class="bc-list-wrap"> 
    <ul class="bc-list bc-ul bc-list-not-standard"> 
     <li class="bc-cate-has-child first" style="display: none;"> 
     </li> 
    </ul> 
    <div class="bc-pagination"> 
     <a class="bc-pagination-next">next</a> 
     <a class="bc-pagination-prev">prev</a> 
    </div> 
</div> 

<div class="bc-list-wrap"> 
    <ul class="bc-list bc-ul bc-list-not-standard"> 
     <li class="bc-cate-has-child first" style="display: none;"> 
     </li> 
    </ul> 
    <div class="bc-pagination"> 
     <a class="bc-pagination-next">next</a> 
     <a class="bc-pagination-prev">prev</a> 
    </div> 
</div> 

回答

1

您需要使用當前元素上下文(即this)並遍歷DOM來定位所需的元素,然後對其執行所需的操作。

您可以使用.closest()後來到達共同祖先.find()可用於定位元素。

$(document).ready(function() { 
    $('.bc-list-wrap').on("click", "a.bc-pagination-next", function() { 
     $(this).closest('.bc-list-wrap').find("li.bc-cate-has-child.first").hide(); 
    }) 

    $('.bc-list-wrap').on("click", "a.bc-pagination-prev", function() { 
     $(this).closest('.bc-list-wrap').find("li.bc-cate-has-child.first").show(); 
    }) 
}); 
+0

是啊,這個工作知府,謝謝。 – user3344734

0

你可以做

$(this).closest('.bc-list-wrap').find("li.bc-cate-has-child.first").hide(); 

而且

$(this).closest('.bc-list-wrap').find("li.bc-cate-has-child.first").show() 

參考closest

0
$(document).ready(function() { 
    $('.bc-list-wrap').each(function() { 
     $('a.bc-pagination-next').click(function() { 
      $(this).parents('.bc-list-wrap').find('li.bc-cate-has-child.first').hide(); 
     }) 

     $('a.bc-pagination-prev').click(function() { 
      $(this).parents('.bc-list-wrap').find('li.bc-cate-has-child.first').show(); 
     }) 
});