[英]Onclick doesn't work as expected on tr
I'm trying to make the onclick
event work for all rows of a table. 我正在尝试使
onclick
事件适用于表的所有行。 But, it doesn't matter what row I click, the event only seems to fire for the last tr
. 但是,我点击哪一行并不重要,事件似乎只是最后一个
tr
。 I made a simple example to illustrate the problem on JSFiddle . 我做了一个简单的例子来说明JSFiddle上的问题。
HTML: HTML:
<table>
<tr>
<td>Test</td>
<td>Test2</td>
</tr>
<tr>
<td>Test</td>
<td>Test2</td>
</tr>
<tr>
<td>Test</td>
<td>Test2</td>
</tr>
<tr>
<td>Test</td>
<td>Test2</td>
</tr>
</table>
Javascript: 使用Javascript:
var table = document.getElementsByTagName( "table" )[0];
for( var contador = 0; contador < table.getElementsByTagName( "tr" ).length; contador++ ){
var line = table.getElementsByTagName( "tr" )[contador];
line.onclick = function() {
line.innerHTML = "Row clicked";
};
}
This is a scoping issue, for
block doesn't create a new scope, so the last value overrides the previous values, you can use a self-invoking function: 这是一个范围问题,
for
块不会创建新的作用域,所以最后一个值会覆盖以前的值,可以使用自调用函数:
(function (line) {
line.onclick = function () {
//line.innerHTML = "Row clicked";
line.cells[0].textContent = "Row clicked";
};
})(table.getElementsByTagName("tr")[contador]);
as mentioned in undefined's answer, for block doesn't create a new scope. 如未定义的答案中所述,对于块,不会创建新范围。
line
gets changed every time the loop is run. 每次循环运行时都会更改
line
。 Use this
instead... 用
this
代替......
var table = document.getElementsByTagName( "table" )[0];
for( var contador = 0; contador < table.getElementsByTagName( "tr" ).length; contador++ ){
var line = table.getElementsByTagName( "tr" )[contador];
line.onclick = function(){
this.innerHTML = "Row clicked...";
};
}
Others replied faster than me, but once you have fixed your issue, also pay attention to the fact that your "innerHTML" will probably not work correctly with IE (your jsfiddle gives a "SCRIPT600: Invalid target element for this operation" in mine)! 其他人回复速度比我快,但是一旦你解决了问题,也要注意你的“innerHTML”可能无法正常使用IE(你的jsfiddle给我的“SCRIPT600:此操作的目标元素无效”) !
JavaScript innerHTML is not working for IE? JavaScript innerHTML不能用于IE吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.