如果我有一个<b>
内部<button>
标签,那么它是标签<b>
的 childNode<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
which 可能是b
元素而不是button
(您想要this
或e.currentTarget
知道您正在引用button
)。
现场示例:
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"
元素是空元素;他们不能有内容,他们的childNodes
收藏总是空的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句