简体   繁体   English

Javascript表行 <tr> onclick函数未执行

[英]Javascript table row <tr> onclick function not executing

I'm trying to have each table row clicked to be highlighted in a color and I'm handling this with a class name but the onclick function is not executing, I tried print statement inside the onclick function to check if it is entering but it's just not. 我试图单击每个表行以将其突出显示为一种颜色,并使用类名进行处理,但是onclick函数未执行,我尝试在onclick函数中使用print语句检查是否正在输入,但它是只是不。

Here is the JS code related to that part: 这是与此部分相关的JS代码:

var rows = document.getElementsByTagName("tr");
    for (var i = 0; i < rows.length; i++)
    {
        rows[i].onclick = function() {
                        this.className = "highlighted";
                        }
    }

Anyone know why this function isn't getting entered? 有人知道为什么没有输入此功能吗?

EDIT: I realized the mistake in the rows variable and I corrected it but the function is still not getting entered and I have no errors on my JS console 编辑:我意识到行变量中的错误,我已将其更正,但该功能仍未输入,并且我的JS控制台上没有错误

使用getElementsByTagName代替getElementsById

Try this 尝试这个

 var rows = document.getElementsByTagName("tr");

Add semicolon 添加分号

rows[i].onclick = function() {
                        this.className = "highlighted";
                        }; // here

It works for me .. Check here : JS Fiddle 它对我有用 ..检查这里: JS小提琴

Use this code. 使用此代码。 Your table rows must have an attribute name with the value "tr" to make this work : 您的表行必须具有值为“ tr”的属性名称才能完成此工作:

var rows = document.getElementsByName("tr");
for (var i = 0; i < rows.length; i++)
{
    rows[i].onclick = function() {
        this.className = "highlighted";
    }
}
var table = document.getElementById("tableId");        
var rows = table.getElementsByTagName("tr");
for (i = 0; i < rows.length; i++) {
    var currentRow = table.rows[i]; 
    var createClickHandler = function(row) {
        return function() { 
            row.className = "highlighted";
        };
    };
    currentRow.onclick = createClickHandler(currentRow);
    }

Use this it will works.... 使用它会起作用....

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

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