在 JavaScript 中附加多个项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36798005/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Append multiple items in JavaScript
提问by brunodd
I have the following function and I am trying to figure out a better way to append multiple items using appendChild()
.
我有以下功能,我试图找出一种更好的方法来使用appendChild()
.
When the user clicks on Add, each item should look like this:
当用户单击添加时,每个项目应如下所示:
<li>
<input type="checkbox">
<label>Content typed by the user</label>
<input type="text">
<button class="edit">Edit</button>
<button class="delete">Delete</button>
</li>
and I have this function to add these elements:
我有这个功能来添加这些元素:
function addNewItem(listElement, itemInput) {
var listItem = document.createElement("li");
var listItemCheckbox = document.createElement("input");
var listItemLabel = document.createElement("label");
var editableInput = document.createElement("input");
var editButton = document.createElement("button");
var deleteButton = document.createElement("button");
// define types
listItemCheckbox.type = "checkbox";
editableInput.type = "text";
// define content and class for buttons
editButton.innerText = "Edit";
editButton.className = "edit";
deleteButton.innerText = "Delete";
deleteButton.className = "delete";
listItemLabel.innerText = itemText.value;
// appendChild() - append these items to the li
listElement.appendChild(listItem);
listItem.appendChild(listItemCheckbox);
listItem.appendChild(listItemLabel);
listItem.appendChild(editButton);
listItem.appendChild(deleteButton);
if (itemText.value.length > 0) {
itemText.value = "";
inputFocus(itemText);
}
}
But you can notice that I am repeating three times the appendChild()
for listItem
. Is it possible to add multiple items to the appendChild()
?
但是你会注意到我重复了三遍appendChild()
for listItem
。是否可以将多个项目添加到appendChild()
?
采纳答案by cн?dk
Personally, I don't see why you would do this.
就我个人而言,我不明白你为什么要这样做。
But if you really need to replace all the appendChild()
with one statement, you can assign the outerHTML
of the created elements to the innerHTML
of the li
element.
但如果你真的需要更换所有appendChild()
有一个说法,您可将outerHTML
创建的元素到innerHTML
了的li
元素。
You just need to replace the following:
您只需要替换以下内容:
listElement.appendChild(listItem);
listItem.appendChild(listItemCheckbox);
listItem.appendChild(listItemLabel);
listItem.appendChild(editButton);
listItem.appendChild(deleteButton);
With the following:
具有以下内容:
listItem.innerHTML+= listItemCheckbox.outerHTML + listItemLabel.outerHTML + editButton.outerHTML + deleteButton.outerHTML;
listElement.appendChild(listItem);
Explanation:
解释:
The outerHTMLattribute of the element DOM interface gets the serialized HTML fragment describing the element including its descendants. So assigning the outerHTML
of the created elements to the innerHTML
of the li
element is similar to appending them to it.
元素 DOM 接口的outerHTML属性获取描述元素及其后代的序列化 HTML 片段。所以分配outerHTML
的创建的元素到innerHTML
了的li
元素类似于他们追加到它。
回答by Slavik
You can do it with DocumentFragment.
你可以用DocumentFragment做到这一点。
var documentFragment = document.createDocumentFragment();
documentFragment.appendChild(listItem);
listItem.appendChild(listItemCheckbox);
listItem.appendChild(listItemLabel);
listItem.appendChild(editButton);
listItem.appendChild(deleteButton);
listElement.appendChild(documentFragment);
DocumentFragments allow developers to place child elements onto an arbitrary node-like parent, allowing for node-like interactions without a true root node. Doing so allows developers to produce structure without doing so within the visible DOM
DocumentFragments 允许开发人员将子元素放置在任意的类似节点的父节点上,从而允许在没有真正根节点的情况下进行类似节点的交互。这样做允许开发人员生成结构,而无需在可见 DOM 中这样做
回答by Sagar V
You can use the appendmethod in JavaScript.
您可以在 JavaScript 中使用append方法。
This is similar to jQuery's append method but it doesnot support IE and Edge.
这类似于 jQuery 的 append 方法,但它不支持 IE 和 Edge。
You can change this code
您可以更改此代码
listElement.appendChild(listItem);
listItem.appendChild(listItemCheckbox);
listItem.appendChild(listItemLabel);
listItem.appendChild(editButton);
listItem.appendChild(deleteButton);
to
到
listElement.append(listItem,listItemCheckbox,listItemLabel,editButton,deleteButton);
回答by Atrahasis
You need to append several children ? Just make it plural with appendChildren
!
你需要追加几个孩子?只需将其设为复数appendChildren
!
First things first :
第一件事:
HTMLLIElement.prototype.appendChildren = function () {
for ( var i = 0 ; i < arguments.length ; i++ )
this.appendChild( arguments[ i ] );
};
Then for any list element :
然后对于任何列表元素:
listElement.appendChildren( a, b, c, ... );
//check :
listElement.childNodes;//a, b, c, ...
Works with every element that has the appendChild
method of course ! Like HTMLDivElement
.
当然适用于每个具有该appendChild
方法的元素!喜欢HTMLDivElement
。
回答by asdru
You can use createContextualFragment, it return a documentFragment created from a string.
It is perfect if you have to build and append more than one Node
s to an existing Element
all together, because you can add it all without the cons of innerHTML
您可以使用 createContextualFragment,它返回一个从字符串创建的 documentFragment。如果您必须将多个Node
s构建Element
并附加到一个现有的所有一起,这是完美的,因为您可以将其全部添加而没有缺点innerHTML
https://developer.mozilla.org/en-US/docs/Web/API/Range/createContextualFragment
https://developer.mozilla.org/en-US/docs/Web/API/Range/createContextualFragment
// ...
var listItem = document.createElement("li");
var documentFragment = document.createRange().createContextualFragment(`
<input type="checkbox">
<label>Content typed by the user</label>
<input type="text">
<button class="edit">Edit</button>
<button class="delete">Delete</button>
`)
listItem.appendChild(documentFragment)
// ...
回答by Simon Suh
You could just group the elements into a single innerHTML group like this:
您可以像这样将元素分组到单个 innerHTML 组中:
let node = document.createElement('li');
node.innerHTML = '<input type="checkbox"><label>Content typed by the user</label> <input type="text"><button class="edit">Edit</button><button class="delete">Delete</button>';
document.getElementById('orderedList').appendChild(node);
then appendChild() is only used once.
那么 appendChild() 只使用一次。
回答by Ricardo Pierre-Louis
It's possible to write your own function if you use the built in arguments object
如果您使用内置参数对象,则可以编写自己的函数
function appendMultipleNodes(){
var args = [].slice.call(arguments);
for (var x = 1; x < args.length; x++){
args[0].appendChild(args[x])
}
return args[0]
}
Then you would call the function as such:
然后你可以这样调用函数:
appendMultipleNodes(parent, nodeOne, nodeTwo, nodeThree)
回答by Pend
Merging the answers by @Atrahasis and @Slavik:
合并@Atrahasis 和@Slavik 的答案:
Node.prototype.appendChildren = function() {
let children = [...arguments];
if (
children.length == 1 &&
Object.prototype.toString.call(children[0]) === "[object Array]"
) {
children = children[0];
}
const documentFragment = document.createDocumentFragment();
children.forEach(c => documentFragment.appendChild(c));
this.appendChild(documentFragment);
};
This accepts children as multiple arguments, or as a single array argument:
这接受子项作为多个参数,或作为单个数组参数:
foo.appendChildren(bar1, bar2, bar3);
bar.appendChildren([bar1, bar2, bar3]);
回答by J C
I would like to add that if you want to add some variability to your html, you can also add variables like this:
我想补充一点,如果您想为 html 添加一些可变性,您还可以添加如下变量:
let node = document.createElement('div');
node.classList.add("some-class");
node.innerHTML = `<div class="list">
<div class="title">${myObject.title}</div>
<div class="subtitle">${myObject.subtitle}
</div>`;