简体   繁体   中英

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.

Here is the JS code related to that part:

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

使用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

Use this code. Your table rows must have an attribute name with the value "tr" to make this work :

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....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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