我编写了一个函数,可以使元素的父元素消失,但它不起作用。这是代码。 HTML:
<div class="att">
<p style="display:inline-block;margin-bottom:2px;cursor:default;">Delete Parent of this element by clicking the image!</p>
<img src="xicon.png" height="16" width="auto" style="display:inline-block;margin-top:3px;cursor:pointer;" onclick="deleteParent(this.id)"/>
</div>
Javascript:
function deleteParent(id){
document.getElementById(id).parentNode.style.display="none";
}
为什么这段代码不起作用?提前致谢!
最佳答案
您的元素没有id
。您应该只引用元素本身,而不是通过 ID。这样它将适用于所有元素,而不必担心它们是否有 ID。
function deleteParent(elem){
elem.parentNode.style.display="none";
}
<div class="att">
<p style="display:inline-block;margin-bottom:2px;cursor:default;">Delete Parent of this element by clicking the image!</p>
<img onclick="deleteParent(this)" src="xicon.png" height="16" width="auto" style="display:inline-block;margin-top:3px;cursor:pointer;"/>
</div>
关于javascript - 使用javascript使父节点消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27365890/