[英]Right way to fill HTML from JS
I am currently working on a page that requires filling a div programmatically with a bunch of HTML like this sample code我目前正在处理一个页面,该页面需要以编程方式使用一堆 HTML 填充 div,例如此示例代码
<div id="Element">
<div class="tooltiptext top both">
<div class="editorMenuButton">
<span>Editor Menu</span>
<img src="https://github.com/..." />
</div>
<div class="diceButton">
<img src="https://github.com/..." />
</div>
</div>
</div>
right now, I am doing this as follows现在,我这样做如下
Element.innerHTML = "<div class='tooltiptext top both'><div class='editorMenuButton'><span>Editor Menu</span><img src='https://github.com/...' /></div><div class='diceButton'><img src='https://github.com/...' /></div></div>";
which definitely works, but using a string to pass HTML seems like probably not the right/best/professional way to do it.这绝对有效,但使用字符串传递 HTML 似乎可能不是正确/最佳/专业的方式。 Is there a better way?
有没有更好的办法?
Thanks!谢谢!
Without involving any external libraries/frameworks, plain javascript allows you to create elements:在不涉及任何外部库/框架的情况下,纯 JavaScript 允许您创建元素:
var mydiv = document.createElement('div');
see https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement ]见https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement ]
You can add various properties as needed:您可以根据需要添加各种属性:
mydiv.className = 'tooltiptext top both';
see https://developer.mozilla.org/en-US/docs/Web/API/Element见https://developer.mozilla.org/en-US/docs/Web/API/Element
Then append these created elements to other elements然后将这些创建的元素附加到其他元素
Element.appendChild(mydiv);
seehttps://developer.mozilla.org/en-US/docs/Web/API/Element/append见https://developer.mozilla.org/en-US/docs/Web/API/Element/append
There are several libraries that make this a bit easier such as metaflux有几个库可以使这更容易一些,例如metaflux
Well, in some cases make sense to use a string, but if you need something more structured, you may use document.createElement
好吧,在某些情况下使用字符串是有意义的,但如果你需要更结构化的东西,你可以使用
document.createElement
https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.