简体   繁体   English

Javascript - 高效插入多个 HTML 元素

[英]Javascript - efficiently insert multiple HTML elements

I'd like to create a select element with a list of a user's Facebook friends (obtained as a JSON object).我想创建一个select元素,其中包含用户的 Facebook 朋友列表(作为 JSON 对象获得)。 I hardcode <select id="friends"></select> into my HTML, then use the following Javascript code to parse the JSON and insert each friend as an option of the select element:我将<select id="friends"></select>硬编码到我的 HTML 中,然后使用以下 Javascript 代码解析 JSON 并将每个朋友作为select元素的option插入:

var msgContainer = document.createDocumentFragment();
for (var i = 0; i < response.data.length; i++) { 
    msgContainer.appendChild(document.createTextNode('<option value="'+response.data[i].id+'">'+response.data[i].name+'</option>'));    
}
document.getElementById("friends").appendChild(msgContainer);

This almost works, except that it inserts &lt;这几乎可以工作,除了它插入&lt; and &gt; &gt; instead of < and > .而不是<> How can I fix it, and is there a more efficient way to insert multiple HTML elements using pure Javascript (not JQuery)?我该如何修复它,是否有更有效的方法使用纯 Javascript(不是 JQuery)插入多个 HTML 元素?

Not sure why you're creating a text node, but it would seem that you want to create option elements, so you could use the Option constructor instead. 不确定为什么要创建文本节点,但似乎您想要创建option元素,因此您可以使用Option构造函数。

var msgContainer = document.createDocumentFragment();

for (var i = 0; i < response.data.length; i++) { 
    msgContainer.appendChild(new Option(response.data[i].name, response.data[i].id));
}
document.getElementById("friends").appendChild(msgContainer);

Or you can use the generic document.createElement() . 或者您可以使用通用document.createElement()

var msgContainer = document.createDocumentFragment();

for (var i = 0; i < response.data.length; i++) {
    var option = msgContainer.appendChild(document.createElement("option"));
    option.text = response.data[i].name;
    option.value = response.data[i].id;
}
document.getElementById("friends").appendChild(msgContainer);

It's nice to have a helper function for creating elements and setting properties at the same time. 很高兴有一个辅助函数来同时创建元素和设置属性。

Here's a simple example of one: 这是一个简单的例子:

function create(name, props) {
    var el = document.createElement(name);
    for (var p in props)
        el[p] = props[p];
    return el;
}

It can be expanded to cover some specific needs, but this will work for most cases. 它可以扩展到满足某些特定需求,但这适用于大多数情况。

You'd use it like this: 你会这样使用它:

var msgContainer = document.createDocumentFragment();

for (var i = 0; i < response.data.length; i++) {
    msgContainer.appendChild(create("option", {
        text: response.data[i].name,
        value: response.data[i].id
    }));
}
document.getElementById("friends").appendChild(msgContainer);

Try this in your for loop instead: 请在你的for循环中尝试这个:

var o = document.createEleent('option');
o.setAttribute('value', response.data[i].id);
o.appendChild(document.createTextNode(response.data[i].name));
msgContainer.appendChild(o);

For those who need similar functionality, you can generate an html snippet using template literals and insert it using innerHTML property.对于那些需要类似功能的人,您可以使用模板文字生成一个 html 片段,并使用innerHTML属性将其插入。 Plus you can set attributes and selected while iterating over the items:另外,您可以在遍历项目时设置属性和选择:

const el = document.createElement('select');
el.innerHTML = ['John', 'Sally', 'Betty'].reduce((acc, prev, i) => {
  if (i === 1) {
    return acc + `<option selected>${prev}</option>`;
  }
  return acc + `<option>${prev}</option>`;
}, '');

const root = document.querySelector('#app');
root.appendChild(el);

In modern browsers this is faster than creating elements one by one imperatively.在现代浏览器中,这比命令式地一个一个地创建元素要快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM