gpt4 book ai didi

javascript - onclick jquery 事件按钮颜色不改变

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

我有三个按钮,Button 1 & Button 2 & Button 3。我的要求是,如果单击 Button 2,则应使用 onclick 事件 更改背景颜色。我试过了,但我做不到。如果我单击按钮 2,按钮 1 的颜色会发生变化。如果我点击 Button 3 , Button 1 的颜色就会改变。

var count = 1;
function setColor(btn, color) {
var btn = 'button';
var color = '#101010';

var property = document.getElementById(btn);
if (count == 0) {
property.style.backgroundColor = "#FFFFFF"
count = 1;
}
else {
property.style.backgroundColor = "red"
count = 0;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<button type="button" id="button" onclick="setColor()">Button 1</button>
<button type="button" id="button" onclick="setColor()">Button 2</button>
<button type="button" id="button" onclick="setColor()">Button 3</button>

My Updated code

 $.ajax({
type: "POST",
data: {city:city,locality:locality},
url: "rentlocalityFilter.php",
success:function(data){

var htmlString='';
$.each( res['data'], function( key, value ) {
var id = value.id;
htmlString +='<a class="col-md-1 icon" style="margin-top:10px;cursor:pointer" onclick="guesttt_login()"><i class="fa fa-heart" aria-hidden="true" style="margin-top: -11px; color: red;" id="button" id="button" onclick="setColor('+value.id+')"></i></a>';

});

}

});


var count = 1;
function setColor() {
var btn = 'button';
var color = '#101010';

var property = document.getElementById(btn);
if (count == 0) {
property.style.backgroundColor = "#FFFFFF"
count = 1;
}
else {
property.style.backgroundColor = "red"
count = 0;
}
}

最佳答案

Html 页面上的 ID 必须是唯一的。

您需要做的就是提供 ID,例如:

<button type="button" id="button1" onclick="setColor('button1')">Button 1</button>
<button type="button" id="button2" onclick="setColor('button2')">Button 2</button>
<button type="button" id="button3" onclick="setColor('button3')">Button 3</button>

并更改您的 javascript 代码:

var count = 1;
function setColor(_btn, color) {
var btn = _btn;
var color = '#101010';

var property = document.getElementById(btn);
if (count == 0) {
property.style.backgroundColor = "#FFFFFF"
count = 1;
}
else {
property.style.backgroundColor = "red"
count = 0;
}
}

关于javascript - onclick jquery 事件按钮颜色不改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45976349/

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