简体   繁体   English

使用DOM在onclick中获取元素id

[英]Using DOM to get element id's inside onclick

I'm trying to access id's of elements fetched by getElementsByTagName but I'm getting an error: 我正在尝试访问由getElementsByTagName提取的元素的id,但是我收到一个错误:

 var divs=document.getElementsByTagName("div"); for(var i=0;i<divs.length;i++){ divs[i].onclick=function(){ alert(divs[i].id); } } 
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Document</title> </head> <body> <div id="1">1</div> <div id="2">2</div> <div id="3">3</div> <div id="4">4</div> <div id="5">5</div> <div id="6">6</div> </body> </html> 

The error is: 错误是:

Uncaught TypeError: Cannot read property 'id' of undefined 未捕获的TypeError:无法读取未定义的属性“id”

When I change 当我改变

alert(divs[i].id); 

to

alert(this.id); 

it works, but I don't understand why this happens. 它有效,但我不明白为什么会这样。

 var divs=document.getElementsByTagName("div"); for(var i=0; i < divs.length;i++){ divs[i].onclick=function(){ alert(this.id); } } 
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Document</title> </head> <body> <div id="1">1</div> <div id="2">2</div> <div id="3">3</div> <div id="4">4</div> <div id="5">5</div> <div id="6">6</div> </body> </html> 

this.id works because: this.id作用是因为:

After you added a onclick to the element, the element call the function if you click on the element. 向元素添加onclick后,如果单击元素,则元素将调用该函数。

After the loop, i will be increased to the length of the divs array (which is 6). 在循环之后, i将增加到divs数组的长度(即6)。 And when the element is clicked and the function is called, divs[6] is undefined and you can't get id of undefined, while the function can understand this points to the clicked element and it will work. 当单击该元素并调用该函数时, divs[6]未定义,并且您无法获得未定义的id,而该函数可以理解this指向被单击的元素并且它将起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM