javascript - 使用javascript使父节点消失

标签 javascript html

我编写了一个函数,可以使元素的父元素消失,但它不起作用。这是代码。 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/

相关文章:

javascript - 如何映射不同的json并从数组中获取数据

javascript - ng-if 指令 : What's the issue here?

css - 如何垂直居中有序列表导航

html - div 高度内的 div 的问题

html - CSS3 : remove blur effect on scale

javascript - req.body 检查是否包含特定字符

javascript - scrollTop() !== 不起作用

表格中的 JavaScript 复选框验证

javascript - 随机.addClass到多个div而不重复

javascript - 为什么我的 Javascript 验证不起作用?