简体   繁体   English

JavaScript 中的插值

[英]Interpolation in JavaScript

I have this jQuery code我有这个jQuery代码

$("#selector").html('<a href=url>text</a>');

where url and text are JavaScript variables.其中urltext是 JavaScript 变量。 How would I evaluate them inside quotes?我将如何在引号内评估它们?

You just concatenate the strings together with + :您只需将字符串与+连接在一起:

$('#selector').html('<a href='+url+'>'+text+'</a>');

While @kingjiv's answer is absolutely right, if you'll be doing a lot of templating with jQuery it might be worth checking out the tmpl * plugin to help keep things organized.虽然@kingjiv 的回答是绝对正确的,但如果您要使用 jQuery 进行大量模板化,则可能值得查看tmpl * 插件以帮助保持井井有条。

* note: This plugin never made it past beta, and is no longer being maintained, the link above is for archival purposes only. *注意:此插件从未通过测试版,并且不再维护,上面的链接仅用于存档目的。

For anyone landing here post 2015: use ES6 template literals .对于 2015 年后登陆这里的任何人:使用ES6 模板文字 These are string literals, enclosed in backticks, which allow embedded expressions.这些是字符串文字,包含在反引号中,允许嵌入表达式。

$('#selector').html(`<a href='${url}'>${text}</a>`);

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

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