Interpolation in JavaScript

女生的网名这么多〃 提交于 2020-01-13 08:39:06

问题


I have this jQuery code

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

where url and text are JavaScript variables. How would I evaluate them inside quotes?


回答1:


You just concatenate the strings together with +:

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



回答2:


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.

*note: This plugin never made it past beta, and is no longer being maintained, the link above is for archival purposes only.




回答3:


For anyone landing here post 2015: use ES6 template literals. These are string literals, enclosed in backticks, which allow embedded expressions.

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


来源:https://stackoverflow.com/questions/6644618/interpolation-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!