我正在尝试在 jQuery 中创建一个代码,将类 active 添加到下一个 div 并将其从前一个 div 中删除,反之亦然。考虑到我稍后要添加的动画。
如果您想查看带有 HTML 和 CSS 的代码: http://codepen.io/salman15/pen/kXVmRG?editors=1010
$(document).ready(function() {
$('#next').click(function() {
var location = $(this).parent().parent();
$('.active').removeClass('active');
$('div').next('#case').addClass('active');
});
$('#prev').click(function() {
var location = $(this).parent().parent();
$('.active').removeClass('active');
$(this).prev('#case').removeClass('active');
});
});
最佳答案
你不应该给你的 div
元素相同的 id
值:那是无效的 HTML。而是使用 "case" 作为 class
值。
要应用 active 类,您可以链接到 removeClass 方法,找到下一个 div
,然后应用 addClass 到该元素。
这是一个简化的片段:
$(document).ready(function(){
$('#next').click(function(){
if ($('.active').next('.case').length) {
$('.active').removeClass('active')
.next('.case')
.addClass('active');
}
});
$('#prev').click(function(){
if ($('.active').prev('.case').length) {
$('.active').removeClass('active')
.prev('.case')
.addClass('active');
}
});
});
.active { background: yellow; border: 1px solid }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="next">
<h1>next</h1>
</div>
<div id="prev">
<h1>prev</h1>
</div>
<div class="case active">content 1</div>
<div class="case">content 2</div>
<div class="case">content 3</div>
关于jquery - 用于更改 div 的上一个和下一个按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38970520/