我下面有一些JS代码,它们基本上代表:悬停具有x1 ID的元素时,使具有x1-1 ID的元素可见,然后在mouseout
上返回默认值隐藏。问题是我还有更多的ID对(x2和x2-1,x3和x3-1等)需要应用相同的代码,并且我不想重复5到6次代码。有一种聪明的方法可以将其包装成几行代码吗?
document.getElementById("x1").addEventListener("mouseover", mouseOver);
document.getElementById("x1").addEventListener("mouseout", mouseOut);
function mouseOver() {
document.getElementById("x1-1").style.visibility = "visible";
}
function mouseOut() {
document.getElementById("x1-1").style.visibility = "hidden";
}
答案 0 :(得分:3)
不使用ID,请使用类。您应该对特定的排他元素使用id,如果您有类似元素的集合,则类更好:
function mouseOver() {
this.style.visibility = "visible";
}
function mouseOut() {
this.style.visibility = "hidden";
}
var classCollection= document.getElementsByClassName("classname");
classCollection.forEach(function(i){
i.addEventListener("mouseover", mouseOver);
i.addEventListener("mouseout", mouseOut);
})
在此处查看更多说明:JavaScript click event listener on class
答案 1 :(得分:0)
您可以遍历元素,并且需要在传递给事件的函数中使用它,例如:
document.querySelectorAll('[id^="x"]').forEach(function(item) {
item.addEventListener("mouseover", mouseOver);
item.addEventListener("mouseout", mouseOut);
});
function mouseOver() {
document.getElementById(this.id + "-1").style.visibility = "visible";
}
function mouseOut() {
document.getElementById(this.id + "-1").style.visibility = "hidden";
}
<span id="x1">Link X-1</span>
<br>
<span id="x2">Link X-2</span>
<br>
<span id="x3">Link X-3</span>
<br>
<span id="x4">Link X-4</span>
<br><br>
<div id="x1-1">Div X-1</div>
<div id="x2-1">Div X-2</div>
<div id="x3-1">Div X-3</div>
<div id="x4-1">Div X-4</div>
答案 2 :(得分:0)
给每个元素一个附加的类,然后使用for
循环:
var len = document.getElementsByClassName("the_class"),
i;
for(i = 1; i <= len; i++) {
document.getElementById("x" + i).addEventListener("mouseover", function () {
mouseOver(this.id);
});
document.getElementById("x" + i).addEventListener("mouseout", function () {
mouseOut(this.id);
});
}
function mouseOver(ID) {
document.getElementById(ID + "-1").style.visibility = "visible";
}
function mouseOut(ID) {
document.getElementById(ID + "-1").style.visibility = "hidden";
}