gpt4 book ai didi

javascript - 如何对具有相似 ID 的多个标签使用 JavaScript 函数?

转载 作者:太空宇宙 更新时间:2023-11-03 19:48:35 24 4
gpt4 key购买 nike

我正在使用 javascript 通过鼠标悬停功能在其他用 html 编写的标签上更改标签文本的颜色。例如:

function mouseoverbox1() {
var mypara = document.getElementById("a1");
mypara.style.color = "green";
}
<div onmouseover="mouseoverbox1()">
<a id="a1">Color</a>
<a id="a1">Names</a>
<a id="a1">Places</a>
</div>

现在,当我运行代码时,只有标签“Color”的颜色变为绿色,而 Names and Places 没有。有什么方法可以让我的函数接受对所有具有相似 ID 的 anchor 标记的更改???

最佳答案

id 需要是唯一的。使用 document.querySelectorAll 和一个类可以满足相同的目标,因为多个元素可以具有相同的 class

//get all the elements with same class name
// iterate it using array#forEach menthod
document.querySelectorAll('.a1').forEach(function(item) {
// add event to each of the element
item.addEventListener('mouseover', function(e) {
this.style.color = "green";
})
})
<div>
<a class="a1">Color</a>
<a class="a1">Names</a>
<a class="a1">Places</a>
</div>

注意:这将在鼠标悬停时为单个文本着色,但如果要求一次为所有文本着色,则将事件处理程序添加到父元素

关于javascript - 如何对具有相似 ID 的多个标签使用 JavaScript 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48073800/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com