【发布时间】:2020-10-11 06:30:18
【问题描述】:
代码的目的是让每个块在鼠标悬停时显示不同的文本。我想再添加 30 个块,但我似乎无法找到一种方法来做到这一点,而不必为每个块创建不同的事件侦听器。是否可以通过使用数组和 for 循环的 mouseover 和 mouseout 的单个事件侦听器来执行此操作?
这就是 Javascript 和 HTML 代码的样子 V
var org = ["Anna", "Bob", "Caroline"]
var change = ["One", "Two", "Three"]
var headone = document.querySelector("#a");
headone.addEventListener('mouseover', function() {
headone.textContent = change[0];
})
headone.addEventListener("mouseout", function() {
headone.textContent = org[0];
})
var headtwo = document.querySelector("#b");
headtwo.addEventListener('mouseover', function() {
headtwo.textContent = change[1];
})
headtwo.addEventListener("mouseout", function() {
headtwo.textContent = org[1];
})
var headthree = document.querySelector("#c");
headthree.addEventListener('mouseover', function() {
headthree.textContent = change[2];
})
headthree.addEventListener("mouseout", function() {
headthree.textContent = org[2];
})
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>repl.it</title>
<style>
table {
width: 80%;
}
td {
width: 20%;
position: relative;
box-shadow: 0 4px 8px 2px rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
background-color: white;
}
td:after {
content: '';
display: block;
margin-top: 100%;
}
td:hover {
background-color: pink;
box-shadow: 0px 4px 24px 5px rgba(129, 120, 255, 1);
}
body {
background-color: lightblue;
}
</style>
</head>
<body>
<table>
<tr>
<td id="a">Anna</td>
<td id="b">Bob</td>
<td id="c">Caroline</td>
</tr>
</table>
</body>
<script src="test.js"></script>
</html>
有什么方法可以让 Javascript 部分更高效地使用数组?而不必为我添加到表中的每个新块创建一个新的 EventListener。
【问题讨论】:
标签: javascript html dom frontend addeventlistener