JavaScript:在字符串内插入变量

4

我有下面这段jQuery代码,用于从另一个页面加载#content div,并将其放入当前页面的#result div中:

$('a').click(function(event){
  $('#result').load('abother_page.html #content');
});

正如您所看到的,我正在将请求文件的名称以及要显示的特定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');
2个回答

12

在这里添加一个空格:

$('#result').load(href + ' #content');
                          ^---- here

以下是对失败尝试的解释:

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

谢谢! 这样修复了问题,感谢您的解释,现在更清楚了。 - stephenmurdoch

0

这已经改变了。

从2015年开始,在ES6中,现在可以使用模板字面量来实现,有一种方法可以在LINK上了解更多信息。

表达式插值

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接