单击锚标记的Javascript / Jquery将addClass添加到特定的LI

时间:2015-07-13 22:03:05

标签: javascript jquery html css

例如,当用户点击具有“active”类的锚标记时,我想将“LI”类添加到具有“list-1”类的link-1并从其他列表中删除“active”类。同样的情况也适用。 任何建议都会非常有用。

<br>
<br>
<ul class="list-item">
    <li class="list-0 active">Product One</li>
    <li class="list-1">Product Two</li>
    <li class="list-2">Product Three</li>
    <li class="list-3">Product Four</li>
</ul>`
<br>
<br> `
<div class="pager-list">
    <a href="#" class="link-0">1</a>
    <a href="#" class="link-1">2</a>
    <a href="#" class="link-2">3</a>
    <a href="#" class="link-3">4</a>
</div>

2 个答案:

答案 0 :(得分:2)

尝试以下方法:

&#13;
&#13;
$(".pager-list").find("a").on("click", function(e) {
    e.preventDefault();
    
    var value = $(this).data("value");
    $(".list-item")
        .find(".list-" + value).addClass("active")
        .siblings().removeClass("active");
});
&#13;
<ul class="list-item">
    <li class="list-1 active">Product One</li>
    <li class="list-2">Product Two</li>
    <li class="list-3">Product Three</li>
    <li class="list-4">Product Four</li>
</ul>
<div class="pager-list">
    <a href="#" data-value="1">1</a>
    <a href="#" data-value="2">2</a>
    <a href="#" data-value="3">3</a>
    <a href="#" data-value="4">4</a>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

<ul class="list-item">
     <li class="list-0 active">Product One</li>
     <li class="list-1">Product Two</li>
     <li class="list-2">Product Three</li>
     <li class="list-3">Product Four</li>
 </ul> 

<div class="pager-list">
  <a href="#" class="link-0" data-rel="list-0">1</a>
  <a href="#" class="link-1" data-rel="list-1">2</a>
  <a href="#" class="link-2" data-rel="list-2">3</a>
  <a href="#" class="link-3" data-rel="list-3">4</a>
</div>



<script>
$('.pager-list').on('click', 'a', function(e){
    e.preventDefault();
    $('.list-item li').removeClass('active');
    $('.list-item li.'+$(this).data('rel')).addClass('active');
});
</script>

或者(没有数据 - 但是链接的顺序和列表项的顺序很重要)

<ul class="list-item">
     <li class="list-0 active">Product One</li>
     <li class="list-1">Product Two</li>
     <li class="list-2">Product Three</li>
     <li class="list-3">Product Four</li>
 </ul> 

<div class="pager-list">
  <a href="#" class="link-0">1</a>
  <a href="#" class="link-1">2</a>
  <a href="#" class="link-2">3</a>
  <a href="#" class="link-3">4</a>
</div>

<script>
    $('.pager-list').on('click', 'a', function(e){
        e.preventDefault();
        var links = $('.pager-list a');
        $('.list-item li').removeClass('active'); 
        $('.list-item li').eq(links.index(this)).addClass('active');
    });
</script>