我有一个变量,使用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="cdnjs.cloudflare/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代码中使用变量?
发布评论