欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

append函数是什么意思(python入门详细教程)

程序员文章站 2023-11-27 18:46:34
append和appendchild是两个常用的方法,用于将元素添加到文档对象模型(dom)中。它们经常可以互换使用,没有太多麻烦,但如果它们是一样的,那么为什么要出现两个api呢?……它们只是相似,...

appendappendchild是两个常用的方法,用于将元素添加到文档对象模型(dom)中。它们经常可以互换使用,没有太多麻烦,但如果它们是一样的,那么为什么要出现两个api呢?……它们只是相似,但不是一样。

append函数是什么意思(python入门详细教程)

append()

此方法用于以node对象或domstring(基本上是文本)的形式添加元素。

插入一个node对象

const parent = document.createelement('div');
const child = document.createelement('p');
parent.append(child);
// 这会将子元素追加到div元素
// 然后div看起来像这样<div> <p> </ p> </ div>

这会将子元素追加到 div 元素,然后 div 看起来像这样

<div> <p> </ p> </ div>

插入domstring

const parent = document.createelement('div');
parent.append('附加文本');

然后 div 看起来像这样的

<div>附加文本</ div>

appendchild()

.append 方法类似,该方法用于dom中的元素,但在这种情况下,只接受一个node对象。

插入一个node对象

const parent = document.createelement('div');
const child = document.createelement('p');
parent.appendchild(child);

这会将子元素追加到 div 元素,然后 div 看起来像这样

<div> <p> </ p> </ div>

插入domstring

const parent = document.createelement('div');
parent.appendchild('appending text');
// uncaught typeerror: failed to execute 'appendchild' on 'node': parameter 1 is not of type 'node'

不同点

.append 接受node对象和domstring,而 .appendchild 只接受node对象。

const parent = document.createelement('div');
const child = document.createelement('p');
// 追加节点对象
parent.append(child) // 工作正常
parent.appendchild(child) // 工作正常
// 追加domstrings
parent.append('hello world') // 工作正常
parent.appendchild('hello world') // 抛出错误

.append 没有返回值,而 .appendchild 返回附加的node对象。

const parent = document.createelement('div');
const child = document.createelement('p');
const appendvalue = parent.append(child);
console.log(appendvalue) // undefined
const appendchildvalue = parent.appendchild(child);
console.log(appendchildvalue) // <p><p>

.append 允许您添加多个项目,而 .appendchild 仅允许单个项目。

const parent = document.createelement('div');
const child = document.createelement('p');
const childtwo = document.createelement('p');
parent.append(child, childtwo, 'hello world'); // 工作正常
parent.appendchild(child, childtwo, 'hello world');
// 工作正常,但添加第一个元素,而忽略其余元素

总结

在可以使用 .appendchild 的情况下,可以使用 .append,但反过来不行。


如果对你有所启发和帮助,可以点个关注、收藏、转发,也可以留言讨论,这是对作者的最大鼓励。

作者简介:web前端工程师,全栈开发工程师、持续学习者。