gpt4 book ai didi

javascript - 附加模板字符串

转载 作者:行者123 更新时间:2023-12-03 13:58:30 25 4
gpt4 key购买 nike

是否可以将模板字符串附加到 div 中?我正在尝试优化我的代码,目前我的代码必须创建元素、添加类、添加文本节点,然后将所有内容附加在一起。我想知道是否可以只创建一个模板字符串然后附加它,以提高效率?我不想用innerHTML删除当前div的html。

socket.on('coinFlip', (result) => {

const messages = document.querySelector('#messages');
const output = `<li class="message broadcast">${result.result}</li>`;

messages.appendChild(output);

});

当前有效的代码是:

socket.on('coinFlip', (result) => {

// Grab dialog box
const messages = document.querySelector('#messages');

// Render messages
const li = document.createElement('li');
li.className = "message broadcast";
const text = document.createTextNode(`${result.result}`);
li.appendChild(text);
messages.appendChild(li);

});

最佳答案

使用Element.insertAdjacentHTML(position, text)

The insertAdjacentHTML() method of the Element interface parses the specified text as HTML or XML and inserts the resulting nodes into the DOM tree at a specified position. It does not reparse the element it is being used on, and thus it does not corrupt the existing elements inside that element. This avoids the extra step of serialization, making it much faster than direct innerHTML manipulation.

Parameters
position
    A DOMString representing the position relative to the element;
    must be one of the following strings:
        - 'beforebegin': Before the element itself.
        - 'afterbegin': Just inside the element, before its first child.
        - 'beforeend': Just inside the element, after its last child.
        - 'afterend': After the element itself.

text
    The string to be parsed as HTML or XML and inserted into the tree.

socket.on('coinFlip', (result) => {

const messages = document.querySelector('#messages');
const output = `<li class="message broadcast">${result.result}</li>`;

messages.insertAdjacentHTML("beforeend", output);

});

关于javascript - 附加模板字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54618582/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com