Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/361.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript:在字符串中插入变量_Javascript_Jquery - Fatal编程技术网

Javascript:在字符串中插入变量

Javascript:在字符串中插入变量,javascript,jquery,Javascript,Jquery,我有以下jquery代码,它从另一个页面将#contentdiv加载到当前页面的#resultdiv中: 如您所见,我正在将请求文件的名称以及要显示的特定div硬编码到随load方法发送的字符串中 我试图使其动态化,但我的代码缺少一些内容: // get the href of the link that was clicked var href=$(this).attr('href'); // pass the href with the load method $('#result').lo

我有以下jquery代码,它从另一个页面将
#content
div加载到当前页面的
#result
div中:

如您所见,我正在将请求文件的名称以及要显示的特定div硬编码到随load方法发送的字符串中

我试图使其动态化,但我的代码缺少一些内容:

// 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');
显然,这不起作用,因为我创建的href变量没有插入字符串中。我该怎么做

我尝试了以下方法,但都没有成功:

// Ruby-style: 
$('#result').load('#{href} #content');
// Concatenating-style
$('#result').load(href + '#content');
添加由“此处”指示的空格:


失败尝试的解释如下:

//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');
这已经改变了

从2015年开始,在
ES6
中,现在可以使用
模板文本来实现这一点
您可以阅读更多关于这一点的信息

表达式插值

var a = 5;
var b = 10;
console.log('Fifteen is ' + (a + b) + ' and\nnot ' + (2 * a + b) + '.');
// "Fifteen is 15 and
// not 20."
在您的情况下

// 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`);

多谢!这就解决了问题,非常感谢你的解释,这让问题变得更加清楚了
var a = 5;
var b = 10;
console.log('Fifteen is ' + (a + b) + ' and\nnot ' + (2 * a + b) + '.');
// "Fifteen is 15 and
// not 20."
// 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`);