Javascript:在字符串中插入变量
Javascript: Interpolating variables inside strings
我有以下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');
添加一个由"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`);
相关文章:
- 如何在windows.location href中插入变量
- 如何在字符串中的特定位置插入变量
- 在样式标记上插入变量
- 如何在第n个shild('')选择器中插入变量
- 如何在 JS 中插入变量
- Javascript:在字符串中插入变量
- 如何在url中插入变量
- 在javascript中以文本形式插入变量
- 如何使用纯JavaScript在内联CSS规则中插入变量
- 在Jquery中插入变量PHP
- Angular 2 -如何在组件中插入变量
- 如何在json url中插入变量
- 揭示模块模式:在哪里为模块访问插入变量
- 在Javascript中插入变量到另一个字符串变量中
- 如何在pug中插入变量字符串
- Phonegap -插入变量到数据库
- 如何使用Javascript加载文件的内容并在其中插入变量
- 在Spaw编辑器中插入变量
- 如何在 JS 中插入变量
- 如何在对象表示法 (JSON) 中插入变量字符串