繁体   English   中英

JavaScript中的字符串插值

[英]String interpolation in JavaScript

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

text = "This is visit number #{numVisits} to this website"

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

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

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

我想要的行为是“点击<a class="ajax" id="schedule"></a> ,当前页面上的content div将被data.htmlschedule div data.html 。如果我手动写入

load("data.html #test"); 

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

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

这已经改变了。

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

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

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

   $('#myModalLabel').html(`Show GRAPH of : ${fundCode}-${funcCode}`); 

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

显示GRAPH:AIP001-_sma

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

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

$('#content').load('data.html #' + $(this).getClass());

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

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

在es6中这是可能的

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/template_strings

`string text ${expression} string text`

试试这个:

$(document).ready(function(){
    $("a.ajax").each(function(){
        var obj = $(this);
        obj.click(function(event){
           alert(obj.attr('id'));
        });
    });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM