gpt4 book ai didi

javascript - 类型错误: Argument 1 of Node.removeChild不是一个对象。删除 div 时

转载 作者:行者123 更新时间:2023-11-28 00:05:56 25 4
gpt4 key购买 nike

我试图删除一个 div,但在控制台中收到此错误。 div 创建得很好,即使当我去检查元素时它也在那里并且它将 div 名称传递给删除函数。

function removeRow(input) {
//$("#".input).remove();
var d = document.getElementById("parentDiv");
var d_nested = document.getElementById(input);
var throwawayNode = d.removeChild(d_nested);
}
<div id="parentDiv">

<div id="div2" class="row">
<label>
the first element
<label>
<a onclick="removeRow(div2)" style="float:right" title="Remove Drug">X </a>
</label>
</label>
</div>
<div id="div3" class="row">
<label>
the Second element
<label>
<a onclick="removeRow(div3)" style="float:right" title="Remove Drug">X </a>
</label>
</label>
</div>
</div>

单击 x 后,我在控制台中收到此错误TypeError:Node.removeChild 的参数 1 不是对象。

最佳答案

为什么不起作用?

您需要在removeRow('div2')中传递一个字符串才能使getElementById(input)成功。

小例子

<html>
<head>
<script>
function removeRow(input){
var d = document.getElementById("parentDiv");
var d_nested = document.getElementById(input); //getElementById() expectes as string as parameter, not an undefined
var throwawayNode = d.removeChild(d_nested);
}
</script>
</head>

<body>
<div id = 'parentDiv'>
<div id = 'div2'>
<a onclick = "removeRow('div2')">X </a>
</div>
<div id = 'div3'>
<a onclick = "removeRow('div3')">Y </a>
</div>
</div>
</body>
</html>

改进

拆分标记和功能是一个很好的做法。此外,我们可以跳过 id 的传递,使其更易于使用。

在这个例子中,我们识别一个类的所有链接以及我们希望由另一个类删除的所有容器。像这样我们在它们之间的 dom 级别上是独立的。

<html>
<head>
<script>
//We are assigning the javascript function to the html
//For this we assigned a class to all elements (anyClass) to find those more efficiently.
function Init(){
//We are getting all anyClass elements
var tL = document.querySelectorAll('.anyClass');

//We assign the remove event for all of them and instead of the string id we pass the element itself (=this)
for(var i=0, j=tL.length; i<j; i++)
tL[i].onclick = function(){
removeRow(this)
}
}

//input:=element and not string id anymore
function removeRow(input){
//Now we are getting the parent for the input element, marked as anyRow so we do not rely on fixed dom structure
//Furthermore we do not need to retrieve parentDiv anymore
var tP = function getParent(e){return (e.className.indexOf('anyRow') !== -1 || !e.parentNode) ? e : getParent(e.parentNode)}(input);

if (tP) tP.parentNode.removeChild(tP)
}
</script>
</head>

<body onload = 'Init()'>
<div id = 'parentDiv'>
<div id = 'div2' class = 'anyRow'><a class = 'anyClass'>X</a></div>
<div id = 'div3' class = 'anyRow'><a class = 'anyClass'>Y</a></div>
<div id = 'div4' class = 'anyRow'><a class = 'anyClass'>Z</a></div>
</div>
</body>
</html>

关于javascript - 类型错误: Argument 1 of Node.removeChild不是一个对象。删除 div 时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31336280/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com