我是 HTML 和 JS 新手。 需要创建动态展开折叠列表。 varparentId = document.getElementById("ABCD") ParentId.setAttribute("数据切换","折叠") ParentId.setAttribute("数据目标","#collapse1") var tag = document.createElement("ul"); tag.setAttribute("id","collapse1") tag.appendChild(document.createTextNode("PQR")) ParentId.appendChild(标签)
尝试将其列为- A B C D 项目质量报告
因此,在这种情况下,当我单击 ABCD 时,PQR 会展开/折叠。 但问题是点击 PQR 时,它又崩溃了。 那么父节点的属性也适用于子节点吗?
最佳答案
这并不是说它获取了其父级的属性,这与事件的处理方式有关,特别是 event bubbling 。当您单击子元素时,如果您单击的所有父元素都会触发单击事件
要在单击附加元素时取消事件冒泡,您需要在新元素的单击处理程序中使用 event.stopPropagation()
附加它们后,执行以下操作
// tag.appendchild code goes here, then do the following
document.querySelector("#collapse1").onclick=function(event){
event.stopPropagation();
}
另外,我应该提到,有了jQuery,这一切都会变得容易10倍。
关于javascript - element.appendChild(node) 是否将父节点的属性应用于子节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32918021/