Javascript:在字符串中插入变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10274081/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript: Interpolating variables inside strings
提问by stephenmurdoch
I have the following jquery code which loads the #content
div from anotherpage, into the #result
div on the currentpage:
我有以下 jquery 代码,它将另一个页面的#content
div加载到当前页面的div 中:#result
$('a').click(function(event){
$('#result').load('abother_page.html #content');
});
As you can see, I'm hard-coding the name of the requested file, along with the specific div I want to display, into the string that is sent with the load method.
如您所见,我将所请求文件的名称以及我想要显示的特定 div 硬编码到与 load 方法一起发送的字符串中。
I'm trying to make this dynamic, but my code is missing something:
我正在尝试使其动态化,但我的代码缺少一些内容:
// get the href of the link that was clicked
var href=$(this).attr('href');
// pass the href with the load method
$('#result').load('href #content');
Obviously this doesn't work because the href variable that i've created is not interpolated in the string. How can I do that?
显然这不起作用,因为我创建的 href 变量没有插入到字符串中。我怎样才能做到这一点?
I tried the following, all without success:
我尝试了以下方法,但都没有成功:
// Ruby-style:
$('#result').load('#{href} #content');
// Concatenating-style
$('#result').load(href + '#content');
回答by Joseph
add a space indicated by "here":
添加一个由“here”表示的空格:
$('#result').load(href + ' #content');
^---- here
an explanation of the failed attempts are as follows:
对失败尝试的解释如下:
//this code used the string "href" as the url
$('#result').load('href #content');
//javascript doesn't have this syntax for wrapping variables like in PHP
$('#result').load('#{href} #content');
//this code appended "#content" like it was a hash tag
$('#result').load(href + '#content');
回答by Curiousdev
This has changed.
这已经改变了。
From 2015 in ES6
this is possible now using Template literals
there is way you can read more about on this LINK
从 2015 年开始,ES6
现在可以使用Template literals
这种方式,您可以在此LINK上阅读更多信息
Expression interpolation
表达式插值
var a = 5;
var b = 10;
console.log('Fifteen is ' + (a + b) + ' and\nnot ' + (2 * a + b) + '.');
// "Fifteen is 15 and
// not 20."
In you case
在你的情况下
// get the href of the link that was clicked
var href=$(this).attr('href');
// pass the href with the load method
$('#result').load(`${href} #content`);