2013-02-20 28 views
0

我有一個腳本,它會在多個框架中找到ElementLevel,並將突出顯示/更改文本顏色。該腳本的作用是,當你將鼠標移動到「快速棕色狐狸」的每個單詞上時,指針下的單詞將會變成紅色並以黃色突出顯示。 frame2中的同一個單詞也會被紅色/突出顯示。請注意,元素ID與類名稱相同。如何使用元素ID getElementsByClassName?

<html><head><title>Test</title> 
    <script> 
    function hey(id) 
     {document.getElementById(id).style.color = "red"; 
     document.getElementById(id).style.backgroundColor = "yellow"; 
     window.parent.frames["frame2"].document.getElementById(id).style.color = "red"; 
     window.parent.frames["frame2"].document.getElementById(id).style.backgroundColor = "yellow";} 
    function bye(id) 
     {document.getElementById(id).style.color = "black"; 
     document.getElementById(id).style.backgroundColor = "white"; 
     window.parent.frames["frame2"].document.getElementById(id).style.color = "black"; 
     window.parent.frames["frame2"].document.getElementById(id).style.backgroundColor = "white";} 
    </script> 
</head> 
<body> 
    <a id="w1" class="w1 w4" onmouseover="hey(this.id)" onmouseout="bye(this.id)">The</a> 
    <a id="w2" class="w2" onmouseover="hey(this.id)" onmouseout="bye(this.id)">quick</a> 
    <a id="w3" class="w3" onmouseover="hey(this.id)" onmouseout="bye(this.id)">brown</a> 
    <a id="w4" class="w1 w4" onmouseover="hey(this.id)" onmouseout="bye(this.id)">fox</a> 
</body></html> 

現在我想編輯此腳本,以便它採用id並按類查找元素。例如,當你鼠標懸停「狐狸」的id =「w4」。我想在鏈接的類中找到「w4」,這樣無論何時被挖掉,「The」和「fox」都將被紅色/突出顯示。我無法弄清楚如何使用id中的值使用getElementsByClassName。有什麼想法嗎?

+1

只需傳遞類名作爲參數:'getElementsByClassName(id)'。更多信息:https://developer.mozilla.org/en-US/docs/DOM/document.getElementsByClassName。順便說一句,你可以直接將元素傳遞給事件處理程序,而不是再次搜索它。 – 2013-02-20 18:01:23

回答

1

getElementsByClassName返回一個數組,你必須遍歷它。嘗試下面的代碼。

var elements = document.getElementsByClassName(id); 

for(var i=0; i<elements.length; i++) 
    elements[i].style.color = "red"; 
+2

'getElementsByClassName()'不_not_返回一個數組,它返回一個[NodeList](https://developer.mozilla.org/en-US/docs/DOM/NodeList)。 – Teemu 2013-02-20 18:11:59

+0

我試過上面的代碼。嗯。不工作。 – parap 2013-02-20 18:12:58

+0

哦,我輸入「i>元素」而不是「我<元素」。我的錯。現在它正在工作。 – parap 2013-02-20 18:25:01

相關問題