为什么Javascript中的removeChild总是删除最后一个孩子而不是从中获得id的孩子?
我有四个带有事件侦听器 onclick 的 div, 调用一个 js 函数,它只执行以下操作:
this.parentNode.removeChild(this);
我希望它删除我单击的 div,但它没有。 相反,它会删除最后一个子项并将后面给出的 id 更改为 已删除子项的 id(第一次单击,最后一个子项),然后进一步单击 其他 div 将给定的 id 倒数到 1。去除 数组中从最后一个到第一个的子节点。
我尝试了很多变体,例如
document.getElementById('parentElementName').removeChild(this.gettAttribute('id'));
or
parent =document.getElementById('parentElementName');
to_be_removed = document.getElementById(this.gettAttribute('id');
parent.removeChild(to_be_removed);
或 childNodes // id = 1,2,3,4
to_be_removed =document.getElementById('box_content').childNodes[this.getAttribute('id')];
parent =document.getElementById('box_content');
parent.removeChild(to_be_removed);
奇怪我可以成功更改可见性或背景颜色:
document.getElementById('box_content').childNodes[this.getAttribute('id')].style.visibility='hidden';
或
i have four divs with the eventlistener onclick,
calling a js function which just does the following :
this.parentNode.removeChild(this);
i expect it to remove the div i clicked on, but it does not.
instead it deletes the last child and changes the id given after to the
id of the removed child (first click, the last child) and by further clicking on the
other divs counts down the given id to one. removing
the childNodes in the array from the last to the first.
i tried a lot of variants, for example
document.getElementById('parentElementName').removeChild(this.gettAttribute('id'));
or
parent =document.getElementById('parentElementName');
to_be_removed = document.getElementById(this.gettAttribute('id');
parent.removeChild(to_be_removed);
or with childNodes // id = 1,2,3,4
to_be_removed =document.getElementById('box_content').childNodes[this.getAttribute('id')];
parent =document.getElementById('box_content');
parent.removeChild(to_be_removed);
strange i can successfully change the visibility or the backgroundColor:
document.getElementById('box_content').childNodes[this.getAttribute('id')].style.visibility='hidden';
or
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
设法重制您想要的内容,请访问 http://jsfiddle.net/6YHcv/ 来查看。这是你所需要的吗?
如果您在 IE 上使用
attachEvent
,则事件处理程序中的this
可能会引用全局对象,而不是您的元素。否则我无法告诉你为什么你的代码不起作用。Managed to remake what you intended, go to http://jsfiddle.net/6YHcv/ to check it out. Is this what you needed?
If you are on IE and use
attachEvent
,this
in the event handler would probably refer to the global object, not your element. Otherwise I can't tell why your code isn't working.我在您的代码中看到一些拼写错误。我认为你的第二个例子应该工作得很好(见评论):
不过也看看这个例子: jsfiddle
它应该像在 onclick 处理程序之后调用函数
this.parentNode.removeChild(this)
一样简单。I see a few typos in your code. Your second example should work just fine, I think (see comments):
Check out this example too, though: jsfiddle
It should be as simple as calling the function
this.parentNode.removeChild(this)
after an onclick handler.