【问题标题】:How to concatenate JavaScript variables into a complexe string with quotes and doubles quotes?如何将 JavaScript 变量连接成带有引号和双引号的复杂字符串?
【发布时间】:2013-04-13 06:58:55
【问题描述】:
 var id_person_value = 4;

$('#message').load("{{ path('MyBundle_ajax_modal_vote', {'id_person' :"+id_person_value+"})   }}", function() {//..

它应该返回

$('#message').load("{{ path('MyBundle_ajax_modal_vote', {'id_person' : 4 })   }}", function() {//..

但这让我回来了:http://mywebsite.com/app_dev.php/+id_person_value+

如何正确注入值?

非常感谢您的帮助!

【问题讨论】:

  • 尝试使用 3 个括号,例如:{{{ path(...) }}}

标签: javascript twig


【解决方案1】:

您可以使用转义字符,例如 \' 在字符串中插入单引号,并使用 \" 作为双引号

【讨论】:

    【解决方案2】:

    不要将东西连接在一起,这既乏味又容易出错,而是尝试格式化功能,类似于其他语言中的printfformat

    str = format("{{ path('MyBundle_ajax_modal_vote', {'id_person' : {0} }) }}", 4)
    

    不幸的是,Javascript 中没有这样的内置函数,但它很容易编写:

    function format(str) {
        var args = [].slice.call(arguments, 1);
        return str.replace(/{(\d+)}/g, function($0, $1) {
            return args[$1]
        })
    }
    

    更多实现请参见JavaScript equivalent of Python's format() function?

    【讨论】:

      【解决方案3】:

      使用简单的双引号来开始和结束字符串“”。如果要在字符串中包含任何引号或双引号,请在引号前使用转义字符 \ 例如,您希望字符串为 s= hello"world 然后 s= "hello\""+"World" 或 s="hello"+"\"" + "world"

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-09-07
        • 2019-06-27
        • 1970-01-01
        • 2015-10-27
        • 2017-02-26
        • 2015-10-29
        • 2017-08-21
        相关资源
        最近更新 更多