首页 > 解决方案 > 如何使用 Jquery 中的 next() 函数将类添加到链接?

问题描述

我在具有活动课程的课程内有一个链接。我想找到该活动类的下一个链接并在新链接中添加活动类。我尝试使用next()功能,但它不起作用。

$("#next").on("click", function() {
  $(".test a.active").next(".test a").addClass("active");
});
.active { color: red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="test"><a href="" class="testx active">a</a></div>
<div class="test"><a href="" class="testx">b</a></div>
<div class="test"><a href="" class="testx">c</a></div>
<div class="test"><a href="" class="testx">d</a></div>
<div class="test"><a href="" class="testx">e</a></div>

<button id="next">click</button>

标签: javascripthtmljquerycss

解决方案


你可以使用.nextfor.test而不是a

$("#next").on("click", function() {
 const cls = $("a.active");   
 cls.removeClass('active') // remove previous active if you need
 cls.closest('.test').next(".test").children('a').addClass("active");
});
.active{
  background-color:green;
  color:white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="test"><a href="" class="testx active">a</a></div>
<div class="test"><a href="" class="testx">b</a></div>
<div class="test"><a href="" class="testx">c</a></div>
<div class="test"><a href="" class="testx">d</a></div>
<div class="test"><a href="" class="testx">e</a></div>

<button id="next">click</button>


推荐阅读