简体   繁体   English

如何将DOM元素嵌入模板文字中

[英]How to embed DOM element inside template literals

Is there any way to embed DOM element inside a template string? 有什么办法可以将DOM元素嵌入模板字符串中?

const btn= document.createElement('button');
btn.addEventListener('click', handler);

someDiv.innerHTML = `
<div>${btn}</div>
`;

It just calls HTMLElement's toString function and renders [object HTMLButtonElement] instead of actual button 它只是调用HTMLElement的toString函数并呈现[object HTMLButtonElement]而不是实际的按钮

You can use Element.outerHTML to get element as string. 您可以使用Element.outerHTML将元素作为字符串获取。 Note it will not append the real btn to div it will copy the element's html and eventListener attached to it will not work. 请注意,它不会将真实的btn附加到div它会复制元素的html, eventListener附加到它的eventListener无效。

If you want the copy elements with its function you can use cloneNode() and appendChild() to insert it to parent. 如果您希望复制元素具有其功能,则可以使用cloneNode()appendChild()将其插入父级。

 let somediv = document.querySelector('#somediv'); const btn= document.createElement('button'); btn.innerHTML = 'Click me'; btn.addEventListener('click',(e) => { somediv.innerHTML = `<div>${btn.outerHTML}</div>` console.log(somediv.innerHTML); }) document.body.appendChild(btn); 
 #somediv{ position:absolute; top:200px; left:200px; padding:10px; background:blue; } 
 <div id="somediv"></div> 

No, the element itself can not be inserted that way. 不,元素本身不能以这种方式插入。 You could serialize it to HTML, but you'll lose any updates you made to the element, such as the event handler. 您可以将其序列化为HTML,但是会丢失对元素所做的所有更新,例如事件处理程序。

Instead you could create the entire structure using HTML, then select the button to add the listener. 相反,您可以使用HTML创建整个结构,然后选择button以添加侦听器。

 someDiv.innerHTML = ` <div><button>click me</button></div> `; someDiv.querySelector("button") .addEventListener('click', handler); var pre = document.querySelector("pre"); function handler(e) { pre.textContent += "foo "; } 
 <div id=someDiv> </div> <pre></pre> 

Element.innerHTML

The Element property innerHTML gets or sets the HTML or XML markup contained within the element. 元素属性innerHTML获取或设置元素中包含的HTML或XML标记。

You can not use innerHTML to insert DOM node created with createElement , for that you have to use methods like ParentNode.append() : 您不能使用innerHTML插入使用createElement创建的DOM节点,因为您必须使用ParentNode.append()类的方法:

 const btn= document.createElement('button'); btn.textContent = 'click'; btn.addEventListener('click', handler); someDiv.innerHTML = ` <div class="inner"></div> `; document.querySelector('.inner').append(btn); function handler(){alert('clicked')} 
 <div id="someDiv"></div> 

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

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