每次用户单击编辑按钮时,我想在我的表(HTLML)表中获取参数。 该表在每行中包含一个编辑按钮,如下所示:
retour.append("<td>");
retour.append("<button id=edit name=edit type=button onClick= editarow()>");
retour.append("<img src=edit.gif />");
retour.append("</button>");
retour.append("</td>");
获取使用javascript单击编辑的每一行的值我执行以下操作:
function editarow(){
var table = document.getElementById("sheet");
var buttons = table.getElementsByTagName("button");
for(var i=0; i<buttons.length; i++) {
if(buttons[i].name=="edit") {
buttons[i].onclick = function()
{
var buttonCell = this.parentNode; //cell
var editThisRow = buttonCell.parentNode; //td
var er=editThisRow.parentNode.attributes[1].value;
alert(er);
}
}
}
}
但我没有得到预期的值。
答案 0 :(得分:1)
您的button
元素中有错误:
onClick= editarow()
应该是
onclick='editarow()'
(“C”应为小写,函数调用引号。)
让我们假设一行如下:
<tr>
<td data-foo="bar">John</td>
<td>Doe</td>
<td>...your edit button...</td>
</tr>
在editarow
中,您可以这样做:
function editarow() {
var row, firstNameCell, lastNameCell;
// `this` is the button, so `this.parentNode` is the cell, and
// `this.parentNode.parentNode` is the row
row = this.parentNode.parentNode;
// The first name cell is the first child
firstNameCell = findElement(row.firstChild);
// The second name cell is its next sibling
lastNameCell = findElement(firstNameCell.nextSibling);
// Their "values" are the text within them, most easily accessed via
// `innerHTML`
alert("First name is " + firstNameCell.innerHTML);
alert("Last name is " + lastNameCell.innerHTML);
// Or if you store data in attributes, you can get them via
// `getAttribute`
alert("data-foo = " + firstNameCell.getAttribute("data-foo"));
}
function findElement(node) {
while (node && node.nodeType != 1) {
node = node.nextSibling;
}
return node;
}
如果您使用jQuery,Prototype,Closure或other libraries,这一切都会变得更轻松。 (例如,上面的findElement
函数非常粗糙;其目的是跳过文本节点等。)
答案 1 :(得分:0)
所以就这样解决了:
function editarow() {
var row, firstNameCell, lastNameCell;
var table = document.getElementById("sheet");
var buttons = table.getElementsByTagName("button");
for(var i=0; i<buttons.length; i++) {
if(buttons[i].name=="edit") {
buttons[i].onclick = function()
{
row = this.parentNode.parentNode;
// The first name cell is the first child
NameCell1 = findElement(row.firstChild);
NameCell2 = findElement(NameCell1.nextSibling);
NameCell3=findElement(NameCell2.nextSibling);
NameCell4=findElement(NameCell3.nextSibling);
NameCell5=findElement(NameCell4.nextSibling);
NameCell6=findElement(NameCell5.nextSibling);
NameCell7=findElement(NameCell6.nextSibling);
// `innerHTML` pour obtenir la valeur
alert("name 1 is " + NameCell1.innerHTML);
alert("name 2 is " + NameCell2.innerHTML);
alert("name 3 is " + NameCell3.innerHTML);
alert("name 4 is " + NameCell4.innerHTML);
alert("name 5 is " + NameCell5.innerHTML);
alert("name 6 is " + NameCell6.innerHTML);
alert("name 7 is " + NameCell7.innerHTML);
}
}}
}
function findElement(node) {
while (node && node.nodeType != 1) {
node = node.nextSibling;
}
return node;
}