javascript - 如何使用 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>
解决方案
你可以使用.next
for.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>
推荐阅读
- phpstorm - 如何在 Windows 的命令行中打开 PhpStorm 中的项目
- c# - Unity3d - 调用公共静态变量性能
- webrtc - 为什么我的 peerconnection 不生成候选冰?
- c# - 实体框架模拟需要全局上下文
- ethereum - 如何在实体映射中使用字符串数组?
- css - 在 react-slick 中,className 与 webpack css-loader 转换的 CSS 文件中的类名不匹配
- symfony - 如何在 symfony 中通过电子邮件发送控制台错误
- node.js - 创建新的 React Native 应用程序
- android - 如何将 Android View 同步渲染到 OpenGL SurfaceView
- php - 动态编辑表格数据,PHP,AJAX