JavaScript中的字符串插值

Ale*_*Mcp 13 javascript jquery

在Ruby中你可以像这样使用字符串插值:

text = "This is visit number #{numVisits} to this website"
Run Code Online (Sandbox Code Playgroud)

这绕过了显式连接的需要.

我正在使用jQuery并且有点像这样:

$(document).ready(function(){
    $("a.ajax").click(function(event){
        $("#content").load("data.html this.getClass");
    });
});
Run Code Online (Sandbox Code Playgroud)

我想要的行为是"点击<a class="ajax" id="schedule"></a>content div在当前页面上替换为schedule divfrom data.html.如果我手动写入

load("data.html #test"); 
Run Code Online (Sandbox Code Playgroud)

这工作,但我希望脚本加载DIV与点击锚点的ID值.任何帮助都会膨胀!

示例页面:http://www.mariahandalex.info/stack/

Mar*_*cos 17

这已经改变了.

截至2015年,现在有一种更好的方法:https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/template_strings

为JS带来了许多像Ruby和PHP这样的语言已经享受过的东西.

例如,在我的jQuery驱动页面中,我使用:

   $('#myModalLabel').html(`Show GRAPH of : ${fundCode}-${funcCode}`); 
Run Code Online (Sandbox Code Playgroud)

在我更新的Firefox和Chrome中安全地呈现为:

显示GRAPH:AIP001-_sma

注意在.html(....)中使用围绕字符串参数的反引号


Ela*_*ich 6

你不能在一个字符串中嵌入javascript代码,但你可以使用'+'将字符串连接到一个对象,就像这样

$('#content').load('data.html #' + $(this).getClass());
Run Code Online (Sandbox Code Playgroud)

关于在字符串中嵌入代码,我认为它没有名称.Groovy将这些字符串称为" Gstring ",而ruby将这些字符串称为" 字符串中表达式替换 ".我不确定它有标准名称.


Ant*_*nes 5

Javascript不解析字符串文字,寻找像Ruby或PHP那样的替换标记.您将不得不使用串联.