在该特定行

时间:2015-10-15 08:00:42

标签: javascript row

我正在动态创建一个html表,如下所示:

var table = document.getElementById("mytable"); 
            var rowcount = document.getElementById("mytable").rows.length;      
            var row = table.insertRow(rowcount);            
            var cell1 = row.insertCell(0);
            var cell2 = row.insertCell(1);
            var cell3 = row.insertCell(2);
            var cell4 = row.insertCell(3);
            var cell5 = row.insertCell(4);

            cell1.innerHTML = rowcount;
            cell2.innerHTML = "a";
            cell3.innerHTML = "b";
            cell4.innerHTML = "c";
            cell5.innerHTML = document.getElementById("select_product_name").value;

连续的最后一列,即cell5,其中包含id

我想要一个函数,使得表中的行的onclick应该得到id,即cell5的值,并且整行应该将颜色更改为红色。 < / p>

  

注意:仅使用Javascript而不是jQuery

1 个答案:

答案 0 :(得分:1)

var table = document.getElementById("mytable"); 
var rowcount = document.getElementById("mytable").rows.length;      

var row = table.insertRow(rowcount);            
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4);

cell1.innerHTML = rowcount;
cell2.innerHTML = "a";
cell3.innerHTML = "b";
cell4.innerHTML = "c";

var id = document.getElementById("select_product_name").value;
cell5.innerHTML = id;

row.onclick = function() {
    // Add a css class to the row
    row.className += ' red';

    // Alert the id
    alert(id);
};