例如这里我有三个图标(fa fa-heart),通常图标颜色为绿色,我的要求是,如果单击图标2,背景颜色应该使用onclick事件更改红色 。再次假设我点击相同的图标2意味着背景颜色应该在绿色中更改,之后我点击图标3意味着背景颜色应该变为红色,我已经尝试但我无法做到这一点。我得到这样的答案,如果我点击图标2,图标1颜色正在改变。如果我单击图标3,图标1颜色正在改变。比如每次图标1都在改变颜色
<div class = "col-md-8 top-a rentListing"> </div>
function searchLocality() {
var city = "something";
var locality = "something";
$.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: green;" id="button" onclick="setColor(' + value.id + ')"></i></a>';
});
$('.rentListing').empty().append(htmlString);
}
});
}
var count = 1;
function setColor(id) {
var btn = 'button';
var color = '#101010';
var property = document.getElementById(btn);
if (count == 0) {
property.style.backgroundColor = "green"
count = 1;
} else {
property.style.backgroundColor = "red"
count = 0;
}
}
答案 0 :(得分:1)
$('.fa-heart').on('click',function(){
$(this).toggleClass('redBackground');
});
每次单击一个心脏时,该类将被切换 - 如果它存在,它将被删除。
这可以进一步发展为
$(this).toggleClass('redBackground greenBackground');
css:
.redBackground{background-color:red}
答案 1 :(得分:0)
请查找更新的代码,在您的代码中,您使用的是静态ID按钮,因此它只会更新。
你必须将实际点击的图标的id传递给javascript函数,并且函数应该存储该图标的第一次点击或之前点击。这需要保存在javascript中
注意:代码未经过测试,只是为您提供了如何实现它的逻辑
<div class = "col-md-8 top-a rentListing"> </div>
function searchLocality() {
var city = "something";
var locality = "something";
$.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: green;" id="' + value.id + '" onclick="setColor(' + value.id + ')"></i></a>';
});
$('.rentListing').empty().append(htmlString);
}
});
}
var count = 1;
var objCount = {};
function setColor(id) {
var btn = id;
var color = '#101010';
if (objCount && objCount[id] != undefined) {
if (objCount[id] == 0) {
objCount[id] = 1;
} else {
objCount[id] = 0;
}
} else {
objCount[id] = 1;
}
var property = document.getElementById(btn);
if (objCount[id] == 0) {
property.style.backgroundColor = "green"
objCount[id] = 1;
} else {
property.style.backgroundColor = "red"
objCount[id] = 0;
}
}