【问题标题】:What are the limitations of appendChild method?appendChild 方法的局限性是什么?
【发布时间】:2022-11-25 14:36:20
【问题描述】:

是否可以将第二个孩子附加到在一行代码中创建的第一个 appendchild 中?

是这样的:

document.body.appendChild(document.createElement('p').appendChild(document.createTextNode('Some Text)));

这工作正常,但我想知道为什么它在一行代码中的工作方式不同。

    let p = document.createElement('p');
    p.appendChild(document.createTextNode('Some Text'));
    document.body.appendChild(p);

【问题讨论】:

  • 单线工作正常,你只是一个错字,有一个未终止的字符串文字。
  • 这两个都对我有效
  • document.body.appendChild(document.createElement('p').appendChild(document.createTextNode('Some Text'))); 你错过了Some Text 末尾的单引号

标签: javascript dom append


【解决方案1】:
document.body.appendChild(document.createElement('p').appendChild(document.createTextNode('Some Text)));

它应该是这样的:

document.body.appendChild(document.createElement('p').appendChild(document.createTextNode('Some Text')));

【讨论】:

    【解决方案2】:

    Element.prototype.append() 返回 undefined,所以

    document.body.appendChild(document.createElement('p').appendChild(document.createTextNode('Some Text')));
    

    基本上是一样的

    const p = document.createElement('p');
    const node = document.createTextNode('Some Text');
    p.appendChild(node);
    document.body.appendChild(undefined);
    

    【讨论】:

    • 是的,append返回undefined,但是appendChild返回插入的元素。 OP 从未使用过append。不过,这不是我的反对意见。
    • Element.prototype.append() 返回未定义“好在 OP 正在使用 appendChild 然后,它返回附加的节点。
    猜你喜欢
    • 1970-01-01
    • 2014-05-11
    • 1970-01-01
    • 2012-07-20
    • 2016-03-21
    • 1970-01-01
    • 1970-01-01
    • 2012-11-01
    • 1970-01-01
    相关资源
    最近更新 更多