如何在JavaScript中使用反引号在html代码中使用变量?

编程入门 行业动态 更新时间:2024-10-28 14:33:31
本文介绍了如何在JavaScript中使用反引号在html代码中使用变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个变量,使用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代码中使用变量?

本文发布于:2023-10-05 08:25:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1467334.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:引号   变量   代码   如何在   JavaScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!