简体   繁体   English

Onclick在tr上没有按预期工作

[英]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]);

http://jsfiddle.net/tx3s580a/ http://jsfiddle.net/tx3s580a/

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...";
    };
}

http://jsfiddle.net/a9xf0nz2/ http://jsfiddle.net/a9xf0nz2/

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.

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