【问题标题】:Can a button element have childNodes?按钮元素可以有子节点吗?
【发布时间】:2018-11-05 16:03:09
【问题描述】:

如果我在<button> 标签内有一个<b>,那么<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 的孩子

【问题讨论】:

    标签: javascript html dom nodes


    【解决方案1】:

    是的,button 元素是有内容的元素。您只是没有正确检查他们的内容;元素上没有 childNode 属性。有childNodes(集合)、firstChildlastChild,以及它们的元素版本childrenfirstElementChildlastElementChild,但没有childNode

    您还使用了Click 而不是click(事件名称区分大小写),并且e.target 可能是b 元素而不是button(您需要@987654336 @ 或 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;
        }
      }
    }
    &lt;button id='mooo'&gt;&lt;b&gt;Cows can't mooo&lt;/b&gt;&lt;/button&gt;

    相比之下,input type="button" 元素是void elements;他们不能有内容,他们的childNodes 收藏总是空的。

    【讨论】:

    • 谢谢 :) 我在这里重写代码时犯了一个错误……点击事件在我的实际代码上很好。另外,为什么要切换大小写,而不是常规的 for 循环?
    • @JamesBaloyi 他正在使用常规循环。 switch 在循环内部,是编写if/then 逻辑的另一种形式。
    猜你喜欢
    • 2020-11-04
    • 2017-04-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多