如何使用javascript更改动态添加元素的属性值

How to change attribute value of dynamically added element with javascript?

本文关键字:元素 属性 添加 动态 何使用 javascript      更新时间:2023-09-26

我最初使用从php-mySQL查询加载的一些数据创建一个表。

我可以在单击按钮时使用Javascript函数向该表动态添加一行。在这个Javascript函数中,成功地创建了"id"answers"name"属性。

我有另一个Javascript函数,它可以删除表中的任何一行,然后依次为每行中的元素重新编号"id"answers"name"属性值。

问题是,当我调用deleteRow函数时,动态添加行中任何元素的"id"answers"name"属性值都不会得到更新。当我在谷歌浏览器中使用"检查元素"功能时,这一点就很明显了。

我在Chrome、Firefox和Safari中都有同样的结果。为什么我不能动态更新这些动态创建的元素的"id"answers"name"属性值?

谢谢你的帮助。

这是我的固定代码:

<script language="javascript">
function addRow(tableID)
{
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.className="recipeIngInput";
element1.type = "text";
element1.name = "ing"+rowCount;
element1.id = "ing"+rowCount;
cell1.appendChild(element1);
var cell2 = row.insertCell(1);
var element2 = document.createElement("input");
element2.className="recipeAmtInput";
element2.type = "text";
element2.name = "amt"+rowCount;
element2.id = "amt"+rowCount;
cell2.appendChild(element2);
var cell3 = row.insertCell(2);
var element3 = document.createElement("img");
element3.onclick = function() {deleteRow('ingredients',this) };
element3.src = "img/redx.jpg";
element3.alt = "delete row";
element3.width = "15";
element3.height = "15";
cell3.appendChild(element3);
}
function deleteRow(tableID,t)
{
var conf=confirm("Delete this ingredient?");
if (conf==true)
    {       
    var table = document.getElementById(tableID);
    table.deleteRow(t.parentNode.parentNode.sectionRowIndex);
    //find the new number of rows in the table after deleting the one row.
    var iRowCount = table.getElementsByTagName('tr').length;
    //loop through all the rows left in the table and re-define their ID and NAMES to be in order starting with xxx1.
    for (var i=1; i<iRowCount; i++)
        {
        row = table.rows[i];
        // Update ingredient id and name values
        setIdAndName(row.cells[0].childNodes[0], "ing"+i);
        // Update amount id and name values
        setIdAndName(row.cells[1].childNodes[0], "amt"+i);
        }
    }
}
function setIdAndName(elmnt,val) {
   elmnt.id = val;
   elmnt.name = val;
   }
</script>
echo '
<table style="margin-left:0" id="ingredients" width="350px" cellspacing="0" border="1">
    <tr>
        <th style="width:200px;">Ingredient Name</th>
        <th style="width:100px;">Amount</th>
        <th style="width:15px;"></th>
    </tr>';

if ($num_results == 0)
{
echo'
    <tr>
        <td><input class="recipeIngInput" type="text" name="ing1" id="ing1"/></td>
        <td><input class="recipeAmtInput" type="text" name="amt1" id="amt1"/></td>
        <td><img onclick="deleteRow("ingredients",this)" src="img/redx.jpg" alt="delete row" width="15" height="15" /></td>
    </tr>';
}
else
{
while($row = mysql_fetch_array($result))
    {
    $ing[$i] = $row['ingredient_id'];
    $amt[$i] = $row['amount'];
    $r = $i + 1;
    echo'
    <tr>
        <td><input class="recipeIngInput" type="text" name="ing'.$r.'" id="ing'.$r.'" value="'.$ing[$i].'"/> </td>
        <td><input class="recipeAmtInput" type="text" name="amt'.$r.'" id="amt'.$r.'" value="'.$amt[$i].'"/> </td>
        <td> <img onclick="deleteRow(''ingredients'',this)" src="img/redx.jpg" alt="delete row" width="15" height="15" /></td>
    </tr>';
    $i++;
    }
}
echo'</table>';
?>
<input type="button" value="Add Another Ingredient" onclick="addRow('ingredients')"         />

我认为问题出在for循环中的这一行:

document.getElementById(tableID).rows[i].cells[0].childNodes[1].childNodes[0].id = "ing"+i;

其他三行都很喜欢。对childNodes[1]的第一个引用应该是childNodes[0]

即使我错了,你也可以通过在那里放一个警报来调试它,看看你是否得到了对元素的引用:

alert(document.getElementById(tableID).rows[i].cells[0].childNodes[1].childNodes[0].id);

另外,PHP生成的HTML也有一个错误:关闭的</center>标记位于关闭的</td>之外。尽管当你可以在TD上使用CSS text-align来实现同样的效果时,你不应该需要中心标签。(<center>已弃用。)

在循环的delete函数中,您有一个没有使用的rowNum变量,整个函数可以按照如下方式进行整理——注意,当您已经在函数开头存储了对该表的引用时,您不需要重复`document.getElementById(tableID):

function deleteRow(tableID,t) {
   if (confirm("Delete this ingredient?")) {
      var table = document.getElementById(tableID);
      var row = t.parentNode.parentNode;
      table.deleteRow(row.sectionRowIndex);
      //find the new number of rows in the table after deleting the one row.
      var iRowCount = table.getElementsByTagName('tr').length;
      alert('Your table has ' + iRowCount + ' rows.');
      //loop through all the rows left in the table and re-define their ID and NAMES to be in order starting with 1xxx.
      for (var i=1; i<iRowCount; i++) {
         row = table.rows[i];
         // Update ingredient id and name values
         setIdAndName(row.cells[0].childNodes[0].childNodes[0], "ing"+i);
         // Update amount id and name values
         setIdAndName(row.cells[1].childNodes[0].childNodes[0], "amt"+i);
      }
   }
}
function setIdAndName(elmnt,val) {
   // uncomment for debugging - alert("DEBUG: Updating element " + elmnt.id);
   elmnt.id = val;
   elmnt.name = val;
}

我不确定,但你的for循环中有一个逐个错误吗?

for (i=1;i<=iRowCount-1;i++)

看起来应该是

for (i=1;i<=iRowCount;i++)

如果是这样的话,那么在for循环中没有接触到表的最后一行,这意味着它没有得到更新。