<!-- give an id to both buttons -->
<span class="tags">Good Car <i id="b1" onclick="myfunc(this)" class="thumbsup fa fa-thumbs-up" ></i> <i id="b2" onclick="myfunc1(this)" class="thumbsdown fa fa-thumbs-down"></i></span>
<script>
function myfunc(x) {
if (x.style.color === "green") {
x.style.color = "grey";
document.getElementById("b2").style.color = "red"; // get the other button and set its color
} else {
x.style.color = "green";
}
}
function myfunc1(x) {
if (x.style.color === "red") {
x.style.color = "grey";
document.getElementById("b1").style.color = "green"; // get the other button and set its color
} else {
x.style.color = "red";
}
}
</script>
使用 jQuery 且没有 id 的替代解决方案是。
<span class="tags">Good Car
<i class="green thumbsup fa fa-thumbs-up" ></i>
<i class="red thumbsdown fa fa-thumbs-down"></i>
</span>
<style>
.green {
background-color: green;
}
.red {
background-color: red;
}
.gray {
background-color: gray;
}
</style>
<script>
$(document).ready(function() { // execute this code after page has loaded
// register a click event listener for anything that has the class "green" or "red"
$(document).on("click", ".green,.red", function() {
if ($(this).hasClass("green")) { // if they clicked on the green button, see if it is NOT active
if (!$(this).hasClass("gray")) {
$(".red").removeClass("gray"); // we are going to become active, so turn off the other button (it might already be off, but that is ok)
}
} else { // must be red
if (!$(this).hasClass("gray")) { // if they clicked on the red button, see if it is NOT active
$(".green").removeClass("gray");// we are going to become active, so turn off the other button (it might already be off, but that is ok)
}
}
$(this).toggleClass("gray"); // flip the active state of this button
});
});
</script>