4

我有以下 jquery 代码将#contentdiv 从另一个页面加载到当前#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');
4

2 回答 2

12

添加一个由“here”表示的空格:

$('#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');
于 2012-04-23T02:25:02.060 回答
0

这已经改变了。

从 2015 年开始,ES6现在可以使用Template literals您可以在此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`);
于 2017-06-23T11:57:57.750 回答