【问题标题】:how can i use RemoveChild Node correctly如何正确使用 RemoveChild 节点
【发布时间】:2012-12-14 14:05:47
【问题描述】:

我想删除表格中的一个元素,

我尝试使用 tr.removeChild(tr.childNodes[2]);

删除我的第三行元素,但它并没有真正起作用

function smile()
{
document.getElementById("p1").style.backgroundImage = 'url(smile.jpg)';
}
function twice()
{
document.getElementById("p2").innerHTML="Smile Smile";
}
function empty()
    {
//this is the part i want to remove , i want to remove the text inside it
    tr.removeChild(tr.childNodes[3]);
}

</script>
</head>

<body>

<table border = "1" >
<form>
<tr>
<th onclick="smile()"><input type="button" name="person1" value="Make it smile!" id="person4" size="30" </th>
<th onclick="twice()"><input type="button" name="person1" value="Make it smile twice!" id="person4" size="30" </th>
<th onclick="empty()"><input type="button" name="person1" value="Make it empty" id="person4" size="30" </th>
</tr>

【问题讨论】:

  • 请注意,重复(和三次)的 id 是无效的,它们必须是唯一的。

标签: javascript node.js removechild


【解决方案1】:

现场演示:http://jsfiddle.net/SbDXC/

我发现您的代码存在一些问题。

首先,您需要定义 tr(参见演示)。

其次,在表格中,使用行和单元格比 childNodes 更可靠。要删除第一行(索引 0)的第三个单元格(索引 2),只需使用:

table.rows[0].removeChild(table.rows[0].cells[2]);​

childNodes 的问题是,在某些浏览器中,换行符将被视为节点。

[编辑] 更短:table.rows[0].deleteCell(2);​

【讨论】:

    【解决方案2】:

    几件事:

    • 您需要在empty() 函数内设置tr,目前它没有设置任何内容。

    • 数组的索引从 0 开始,因此您要告诉它删除第 4 个孩子。尝试将其更改为:

      tr.removeChild(tr.childNodes[2]);

    【讨论】:

    • 它不起作用,而且我在发布代码时弄错了它,我试过 tr.removeChild(tr.childNodes[2]);
    • 看我的更新,你需要在你的empty方法中设置tr变量
    猜你喜欢
    • 1970-01-01
    • 2016-03-03
    • 1970-01-01
    • 2016-04-21
    • 1970-01-01
    • 2014-03-22
    • 1970-01-01
    • 2019-10-28
    相关资源
    最近更新 更多