[英]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
了解有關此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`);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.