Javascript:在字符串中插入变量

Javascript: Interpolating variables inside strings

本文关键字:插入 变量 字符串 Javascript      更新时间:2023-09-26

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

$('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');

添加一个由"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');

这已经改变了。

从 2015 年到 ES6 现在可以使用Template literals您可以通过此链接阅读更多信息

表达式插值

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