简体   繁体   English

JavaScript中的字符串插值

[英]String interpolation in JavaScript

In Ruby you can use string interpolation like so: 在Ruby中你可以像这样使用字符串插值:

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

This bypasses the need for explicit concatenation. 这绕过了显式连接的需要。

I'm working with jQuery and have a bit like this: 我正在使用jQuery并且有点像这样:

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

The behavior I want is "click on <a class="ajax" id="schedule"></a> and the content div on the current page is replaced by the schedule div from data.html . If I manually write in 我想要的行为是“点击<a class="ajax" id="schedule"></a> ,当前页面上的content div将被data.htmlschedule div data.html 。如果我手动写入

load("data.html #test"); 

that works, but I want the script to load the DIV with the ID value of the anchor clicked. 这工作,但我希望脚本加载DIV与点击锚点的ID值。 Any help would be swell! 任何帮助都会膨胀!

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

This has changed. 这已经改变了。

As of 2015 there is now a better way: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/template_strings 截至2015年,现在有一种更好的方法: https//developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/template_strings

Bringing to JS what many languages like Ruby and PHP have enjoyed already. 为JS带来了许多像Ruby和PHP这样的语言已经享受过的东西。

For example, in my jQuery driven page I use: 例如,在我的jQuery驱动页面中,我使用:

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

Which safely renders in my updated Firefox and Chrome as: 在我更新的Firefox和Chrome中安全地呈现为:

Show GRAPH of : AIP001-_sma 显示GRAPH:AIP001-_sma

Note the use of backticks surrounding the string param in .html( .... ) 注意在.html( .... )中使用围绕字符串参数的反引号

You cannot embed javascript code inside a string, but you can concatenate a string to an object using '+' like so 你不能在一个字符串中嵌入javascript代码,但你可以使用'+'将字符串连接到一个对象,就像这样

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

About embedding code in a string, I don't think it has a name. 关于在字符串中嵌入代码,我认为它没有名称。 Groovy calls those strings " Gstring "s, and ruby calls those ' Expression substitution in strings '. Groovy将这些字符串称为“ Gstring ”,而ruby将这些字符串称为“ 字符串中表达式替换 ”。 I'm not sure it has a standard name. 我不确定它有标准名称。

Javascript doesn't parse string literals looking for replacement markers like Ruby or PHP does. Javascript不解析字符串文字,寻找像Ruby或PHP那样的替换标记。 You will have to use concatenation. 您将不得不使用串联。

Try this: 试试这个:

$(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