我有 3 个带有 ID 的 img
元素。当我单击该元素时,我会像这样更改 img src
$("#employee").on("click", function(){
var x = $(this);
var y = $(this).attr("src");
if($(this).attr("src") == "images/employee.svg")
{
$(this).attr("src", "images/employee_selected.svg");
}
else
{
$(this).attr("src", "images/employee.svg");
}
});
$("#team").on("click", function(){
var x = $(this);
var y = $(this).attr("src");
if($(this).attr("src") == "images/team.svg")
{
$(this).attr("src", "images/team_selected.svg");
}
else
{
$(this).attr("src", "images/team.svg");
}
});
$("#product").on("click", function(){
var x = $(this);
var y = $(this).attr("src");
if($(this).attr("src") == "images/product.svg")
{
$(this).attr("src", "images/product_selected.svg");
}
else
{
$(this).attr("src", "images/product.svg");
}
});
这段代码似乎非常重复,我想知道是否有办法使用 switch 语句之类的东西在单个 .on click 函数
中执行此操作。
如何将其简化为单个语句?
最佳答案
考虑以下代码:
$(function() {
$(".svg").on("click", function() {
var x = $(this);
var non = "images/" + x.attr("id") + ".svg";
var sel = "images/" + x.attr("id") + "_selected.svg";
if (x.attr("src").indexOf("_") < 0) {
x.attr("src", sel).toggleClass("selected");
console.log(sel);
} else {
x.attr("src", non).toggleClass("selected");
console.log(non);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<img id="employee" src="images/employee.svg" class="svg image" />
<img id="team" src="images/team.svg" class="svg image" />
<img id="product" src="images/employee.svg" class="svg image" />
</div>
我们可以提取被单击元素的SRC
,并根据特定条件执行特定操作。这适用于具有类选择器 svg
的所有元素。
希望有帮助。
关于javascript - 简化不同选择器的重复 onclick 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53530113/