如果我有一个 <b>
里面<button>
标签,是 <b>
因此 <button>
的子节点标签?考虑下面的代码:
<button id='mooo'><b>Cows can't mooo</b></button>
Javascript:
x = document.getElementById('mooo');
x.addEventListener("Click", mooo);
function mooo(e){
if(e.target.childNode == "B"){
console.log("B is a child of Button");
}else{
console.log("B is not a child of Button");
}
代码返回后者,但我只需要确定 B 是否确实不是 BUTTON 的子元素
最佳答案
是的,button
元素是带有内容的元素。你只是没有正确检查他们的内容;元素上没有 childNode
属性。有 childNodes
(集合)、firstChild
、lastChild
及其元素版本 children
、firstElementChild
和 lastElementChild
,但没有 childNode
。
您还使用了 Click
而不是 click
(事件名称区分大小写),并且 e.target
可能是b
元素而不是 button
(您希望 this
或 e.currentTarget
知道您正在引用按钮
)。
实例:
var x = document.getElementById('mooo');
x.addEventListener("click", mooo);
function mooo() {
if (this.firstElementChild.tagName == "B") {
console.log("B is a child of Button");
} else {
console.log("B is not a child of Button");
}
console.log("Contents of the button:");
for (let child = this.firstChild; child; child = child.nextSibling) {
switch (child.nodeType) {
case 1: // Element
console.log(child.tagName + " element, innerHTML = " + child.innerHTML);
break;
case 3: // Text node
console.log("Text node, nodeValue = " + child.nodeValue);
break;
default:
console.log(child.nodeName);
break;
}
}
}
<button id='mooo'><b>Cows can't mooo</b></button>
相比之下,input type="button"
元素为 void elements ;他们不能有内容,他们的 childNodes
集合始终为空。
关于javascript - 按钮元素可以有子节点吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50543016/