gpt4 book ai didi

javascript - 单击时更改文本颜色

转载 作者:行者123 更新时间:2023-11-30 20:42:34 25 4
gpt4 key购买 nike

我遇到了一个问题,用户点击不是后台代码,再次点击还得回到上一个。这种情况正在发生,但是再次执行所有这些操作并没有成功,就好像 jquery 只执行了一次。

偶数段有颜色,奇数段有颜色。

<!DOCTYPE html>
<html>
<body>

<style>

p:nth-child(2n+1){
color: green;
background-color: red;
}

p:nth-child(2n){
color: yellow;
background-color:blue;
}

</style>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<p>6</p>

<script>

$('p:nth-child(2n+1)').click(function(){
$(this).css('background-color','black').css('color','white');
$('p:nth-child(2n+1)').click(function(){
$(this).css('background-color','red').css('color','green');
});
});

$('p:nth-child(2n)').click(function(){
$(this).css('background-color','black').css('color','white');
$('p:nth-child(2n)').click(function(){
$(this).css('background-color','blue').css('color','yellow');
});

});


</script>


</body>
</html>

最佳答案

首先你不需要注册两次点击事件,也不需要将奇数和偶数分开,你可以切换一个类:

$(function(){
// p:nth-child(2n), p:nth-child(2n+1)
// p:even, p:odd
// p
$('p').click(function() {
$(this).toggleClass("blackwhite");
});
});
p:nth-child(2n+1){
color: green;
background-color: red;
}

p:nth-child(2n){
color: yellow;
background-color:blue;
}

p.blackwhite {
background-color:black;
color:white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<p>6</p>

关于javascript - 单击时更改文本颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49088388/

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