簡體   English   中英

如何對多個具有相似ID的標簽使用javascript函數?

[英]How to use javascript function for more than one tag with similar id?

我正在使用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”的顏色變為綠色,而不是“名稱和位置”。 有什么辦法可以讓我的函數接受所有具有相似ID的錨標記的更改???

您應該改用類。

然后,在Javascript中,您可以獲得具有相同類的所有元素的數組。

 function handleBoxMouseover () { // Get all child elements with the class "a1" and save them into an array var childElements = document.getElementsByClassName('a1'); // iterate through the new array and change the color by the array index for (var i = 0; i < childElements.length; i++) { childElements[i].style.color = 'green'; } } 
 <div onmouseover="handleBoxMouseover()"> <a class="a1">Color</a> <a class="a1">Names</a> <a class="a1">Places</a> </div> 

僅供參考:

除了更改內聯樣式之外,您還可以向childElements添加一個類以更改顏色。

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> 

注意:這將在鼠標懸停時為單個文本着色,但是如果要求一次性為所有文本着色,則將eventhandler添加到父元素

在每個a上添加mouseoverbox1()而不是使用參數this的父div 然后在函數內部首先重置所有acolor屬性。 最后僅將color設置為當前通過a

請注意:id在文檔中應該是唯一的。 您可以改用class

請嘗試以下方式:

 function mouseoverbox1(that){ document.querySelectorAll("#tagContainer > a.a1").forEach(function(el){ el.style.color = ""; }); that.style.color = "green"; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="tagContainer"> <a class="a1" onmouseover="mouseoverbox1(this)">Color</a> <a class="a1" onmouseover="mouseoverbox1(this)">Names</a> <a class="a1" onmouseover="mouseoverbox1(this)">Places</a> </div> 

有什么辦法可以讓我的函數接受所有具有相似ID的錨標記的更改???

Id必須是唯一的,否則您會遇到類似這樣的問題。

也就是說,如果要保持id不變,則不應使用getElementById ,而應使用querySelectorAll

function mouseoverbox1(){
    document.querySelectorAll("[id='a1']").forEach( function( ele ){
       ele.style.color = "green";
    });
}

演示版

 function mouseoverbox1(){ document.querySelectorAll("[id='a1']").forEach( function( ele ){ ele.style.color = "green"; }); } 
 <div onmouseover="mouseoverbox1()"> <a id="a1">Color</a> <a id="a1">Names</a> <a id="a1">Places</a> </div> 

由於您已經有許多JS解決方案,因此我將針對該問題發布缺少的最簡單(可能是最合適)的解決方案:CSS。

 div a:hover { color: green; } 
 <div> <a id="a1">Color</a> <a id="a1">Names</a> <a id="a1">Places</a> </div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM