简体   繁体   English

是否可以将元素的textContent分配为JS中的HTML代码?

[英]is it possible to assign the textContent of an element to be HTML code in JS?

I know you can use backticks to do this regularly, but are you able to concatenate those backticks? 我知道您可以定期使用反引号,但是您可以将那些反引号串联起来吗?

For example, will 例如,将

let bar = 42;
let foo = document.createElement("div");
foo.innerHTML = `<div> this number is ` + bar + ` </div>`;

be.. 是..

<div> this number is 42 </div>

If not, is there another way to do this? 如果没有,还有其他方法吗? I am trying to create create elements with textContent that is only in my JS file 我正在尝试使用仅在我的JS文件中的textContent创建create元素

Backticks are meant to make it easier for you to combine strings. 反引号旨在使您更容易组合字符串。 For example, 例如,

`This is a variable: ${testVariable}`;

is the same thing as 和...一样

"This is a variable: " + testVariable;

In your case, both will result in a string, so you would be able to use both of them to create elements. 在您的情况下,两者都将产生一个字符串,因此您将能够使用它们两者来创建元素。

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

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