2017-08-16 87 views
-1

我正在學習關於JavaScript中的addEventListener,當我輸入驗證碼:的addEventListener的JavaScript

test(); 
function test(){ 
    var td = document.getElementsByTagName("td"); 
    td.addEventListener('mouseenter', function(){ 
     td.style.background = "green"; 
    }); 
} 

沒有奏效。誰能解釋爲什麼?

+0

'.getElementsByTagName()'返回一個列表。該列表沒有'.addEventListener()'方法。列表中的單個元素具有'.addEventListener()'方法,因此您需要遍歷列表(如鏈接的副本)。 – nnnnnn

+0

Document.getElementsByTagName返回一個節點列表,如果你想應用addEventListener,你需要使用Array.prototype.slice.apply到documet.getElementsByTagName,並且在使用for或forEach函數將addEventListener應用到數組中的每個td元素後 –

回答

0

getElementsByTagName回報的HTMLCollection,所以你需要傳遞您要添加事件的元素的索引,或環比收集到的事件添加到每個元素

function test(){ 
    // selecting only first element from the collection 
    var td = document.getElementsByTagName("td")[0]; 
    td.addEventListener('mouseenter', function(){ 
     td.style.background = "green"; 
    }); 
} 

test(); 

加入addListener添加到集合中的所有元素

function test(){ 
var cells = table.getElementsByTagName("td"); 
for (var i = 0; i < cells.length; i++) { 
cells[i].addEventListener('mouseenter', function(){ 
      this.style.background = "green"; 
     }); 

}}; 
test() 
相關問題