按钮单击动态创建的表中的每一行以检索相应行的列值

时间:2012-04-27 08:58:11

标签: javascript html

//按钮单击动态创建的表中的每一行以检索相应行的列值

var rowCount = result.rows.length;// to count numrows coming from database
for(var j=1; j<=rowCount; j++)
{
var row = result.rows.item(j-1); // creating rowindex in the table
exercise =row.Exercise; // value from database 
time= row.Time; // value from database 
userid = row.UserId // value from database

var table = document.getElementById("check"); // table id 
var row1 = table.insertRow(j); // Insert Row To Table 

 var cell1 = row1.insertCell(0);
 var element1 = document.createElement("input");
 element1.type = "text";
 element1.value = exercise;
 cell1.appendChild(element1);

 var cell2 = row1.insertCell(1);
 var element2 = document.createElement("input");
 element2.type = "text";
 element2.value = time;
 cell2.appendChild(element2);

 var cell3= row1.insertCell(2);
 var element3 = document.createElement("input");
 element3.type = "button";
 element3.value = "edit";

var cell4= row1.insertCell(3);

var element4 = document.createElement(“input”);

element4.value = userid;
cell4.appendChild(element4);
cell4.style.dispalay="none";

element3.addEventListener('click', function () { 
alert('event fired!'); 
// get the userid value of the clicked  button as an alert 
});
}

2 个答案:

答案 0 :(得分:0)

尝试为列提供一些行ID和类,然后您可以使用

jQuery(".your_class").click(function(){
var column_value = jQuery(this).html();
});

你的意思是这样吗?

答案 1 :(得分:0)

首先为每个元素分配一个唯一的id。例如:

var cell4= row1.insertCell(3);
var element4= document.createElement("input");
element4.type = "text";
element4.value = userId; // from DB
element4.id = "element4-" + j;
cell4.appendChild(element4);

指定edit按钮id = j。

var cell3= row1.insertCell(2);
var element3 = document.createElement("input");
element3.type = "button";
element3.value = "edit";
element3.id = j;
cell3.appendChild(element3);

然后将onclick处理程序分配给for循环内的编辑按钮,如下所示:

element3.onclick=doSomething;

创建一个函数doSomething()

function doSomething() {  
   for(var j=1; j<=rowCount; j++)
   {    
       var value = document.getElementById("element" + j + "-" + this.id).value;
       alert(value);
   }
}

希望这有帮助。