如何在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><a href="">a</a></div>
<div><a href="">b</a></div>
<div><a href="">c</a></div>
<div><a href="">d</a></div>
<div><a href="">e</a></div>
<button>click</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div><a href="">a</a></div>
<div><a href="">b</a></div>
<div><a href="">c</a></div>
<div><a href="">d</a></div>
<div><a href="">e</a></div>
<button>click</button>
回答
你可以用.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;
}