我正在尝试在我的li元素上添加类。我想在点击时添加类。当我点击按钮时,它会在当前的li上添加css类。就像我第一次点击它然后它第一次活跃。第二次点击后,它在第二个li上激活,
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("li:first").addClass("intro");
});
});
</script>
<style>
.intro {
font-size: 150%;
color: red;
}
</style>
</head>
<body>
<h1>This is a heading</h1>
<li>This is a heading</li>
<li>This is a heading</li>
<li>This is a heading</li>
<li>This is a heading</li>
<li>This is a heading</li>
<li>This is a heading</li>
<li>This is a heading</li>
<li>This is a heading</li>
<button>Add a class name to the first p element</button>
</body>
</html>
答案 0 :(得分:1)
计算点击事件并应用eq()
。li
长度为8
。在7到达后应用条件,计数重置为0
var c = 0;
$(document).ready(function() {
$("button").click(function() {
if (c > 7) {
c = 0;
}
$("li").removeClass('intro')
$("li").eq(c).addClass("intro");
c++;
});
});
&#13;
.intro {
font-size: 150%;
color: red;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<body>
<h1>This is a heading</h1>
<li class="intro">This is a heading</li>
<li>This is a heading</li>
<li>This is a heading</li>
<li>This is a heading</li>
<li>This is a heading</li>
<li>This is a heading</li>
<li>This is a heading</li>
<li>This is a heading</li>
<button>Add a class name to the first p element</button>
</body>
</html>
&#13;
使用prev and next
更新了幻灯片
var c = 0;
$(document).ready(function() {
$("button").click(function() {
$(this).attr('data') == 'next' ? c++ : c--;
if (c > 7) {
c = 0;
}
$("li").removeClass('intro')
$("li").eq(c).addClass("intro");
});
});
&#13;
.intro {
font-size: 150%;
color: red;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<body>
<h1>This is a heading</h1>
<li class="intro">This is a heading</li>
<li>This is a heading</li>
<li>This is a heading</li>
<li>This is a heading</li>
<li>This is a heading</li>
<li>This is a heading</li>
<li>This is a heading</li>
<li>This is a heading</li>
<button data="next">next</button>
<button data="prev">prev</button>
</body>
</html>
&#13;
答案 1 :(得分:0)
也许你可以这样做:
$(document).ready(function(){
$("button").click(function(){
//Find the li with the active class and add your other class
$("li.active").addClass("your-class");
});
})
这是一个演示片段
$(document).ready(function(){
$("button").click(function(){
$("li.active").addClass('foo-class')
})
})
&#13;
.foo-class{
color:red;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li class='active'>Active</li>
<li> Non active</li>
</ul>
<button>Click me</button>
&#13;
答案 2 :(得分:0)
使用活动类查找li
并添加其他类
$(document).ready(function(){
$("button").click(function(){
// Find li and add other class
var l=$("body").find("li:first-child");
$(l).addClass("your-class");
});
})