gpt4 book ai didi

javascript - jQuery:在当前元素上添加类

转载 作者:行者123 更新时间:2023-12-03 04:24:08 25 4
gpt4 key购买 nike

我正在尝试在我的 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>

最佳答案

对点击事件进行计数并使用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++;

});
});
.intro {
font-size: 150%;
color: red;
}
<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>

用幻灯片的上一张和下一张更新了答案

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");


});
});
.intro {
font-size: 150%;
color: red;
}
<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>

关于javascript - jQuery:在当前元素上添加类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43818038/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com