如何在JavaScript中使用反引号在html代码中使用变量? [英] How to use a variable in html code using backtick in JavaScript?
问题描述
我有一个变量,使用JavaScript反引号定义的值很少.如何在反引号中使用另一个变量?
I have a variable there is define few value with using JavaScript backtick. How can I use another variable with backtick?
var liElem = '';
$('button').click(function(){
var newData = 'This is new data'
liElem = `<ul>
<li class=" ' + newData + ' ">Good news</li>
<li class="icon-text-dark-yellow">Fair</li>
<li class="icon-text-dark-red">Poor</li>
<li class="icon-text-light-gray">N/A</li>
</ul>`;
console.log(liElem);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>click</button>
为什么 newData
变量在内部不可读?JavaScript反引号?有什么办法吗?
Why newData
variable is not readable inside? JavaScript backtick? There is any way to do this?
答案将不胜感激!
推荐答案
它被称为模板文字,如文档所述:
It is called template literals, as the documentation states:
模板文字是允许嵌入表达式的字符串文字.您可以使用多行字符串和字符串插值功能.在ES2015规范的先前版本中,它们被称为模板字符串".
Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them. They were called "template strings" in prior editions of the ES2015 specification.
您要执行的操作称为表达式插值,您可以使用 $ {variableName}
来实现.
What you want to do is called expression interpolation what you can achieve with ${variableName}
.
您需要使用以下内容:
const newData = 'This is new data';
const liElem = `<ul>
<li class="${newData}">Good news</li>
<li class="icon-text-dark-yellow">Fair</li>
<li class="icon-text-dark-red">Poor</li>
<li class="icon-text-light-gray">N/A</li>
</ul>`;
console.log(liElem);
希望对您有帮助!
这篇关于如何在JavaScript中使用反引号在html代码中使用变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!