gpt4 book ai didi

javascript - 多按钮点击事件

转载 作者:太空宇宙 更新时间:2023-11-04 06:31:31 24 4
gpt4 key购买 nike

在一个有多个按钮的网站上工作,所有我希望按钮在你点击它们时改变颜色。例子。单击按钮 1,按钮 1 从白色变为黄色。单击按钮 2,按钮 2 从白色变为黄色。现在我在按钮代码中有 onclick 并且它可以工作,除了它会同时更改所有按钮。

$(document).ready(function() {
$(".button").click(function() {
$(".button").css('background', 'yellow');
});
});
.button {
background-color: #FFFFFF;
/* White */
border: 2px solid #f44336;
color: black;
padding: 10px 10px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 30px;
border-radius: 50%;
width: 60px;
text-align: center;
cursor: pointer
}

.disabled {
background-color: #FF0000;
/* Red */
color: white;
cursor: not-allowed;
}

.button-clicked {
background-color: #FFFF00;
/* Yellow */
}

td:not(:first-child) {
padding-top: 5px;
padding-bottom: 5px;
padding-right: 5px;
}
<script src="Https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table width="100%" border=1>
<tr>
<td align="center"><button class="button" id="1" onclick="myFunction()">1</button></td>
<td align="center"><button class="button" id="2" onclick="myFunction()">2</button></td>
<td align="center"><button class="button" id="3" onclick="myFunction()">3</button></td>
</tr>
</table>

最佳答案

这是使用您提供的代码的解决方案,您只需将 $(".button").css('background', 'yellow'); 更改为 $(this .css('背景', '黄色');

您还可以从 HTML 中删除 onclick。

虽然这是您的代码的一个有效片段,但其他人已经为这个问题提供了更好的解决方案。

<!DOCTYPE html>
<html>

<head>
<script src="Https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$(".button").click(function () {
$(this).css('background', 'yellow');
});
});
</script>
<style>
.button {
background-color: #FFFFFF;
/* White */
border: 2px solid #f44336;
color: black;
padding: 10px 10px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 30px;
border-radius: 50%;
width: 60px;
text-align: center;
cursor: pointer
}

.disabled {
background-color: #FF0000;
/* Red */
color: white;
cursor: not-allowed;
}

.button-clicked {
background-color: #FFFF00;
/* Yellow */
}

td:not(:first-child) {
padding-top: 5px;
padding-bottom: 5px;
padding-right: 5px;
}
</style>
</head>

<body>
<table width="100%" border=1>
<tr>
<td align="center"><button class="button" id="1">1</button></td>
<td align="center"><button class="button" id="2">2</button></td>
<td align="center"><button class="button" id="3">3</button></td>
</body>

</html>

关于javascript - 多按钮点击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54637329/

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