【问题标题】:jQuery .each with Smarty variable in .tpljQuery .each 在 .tpl 中带有 Smarty 变量
【发布时间】:2012-12-03 20:25:25
【问题描述】:

我有一个带有以下 html 的页面,该页面使用不同的电话号码多次出现:

<div class="crm-content crm-contact_phone primary">
    <span>5555551212</span>
</div>

电话号码本身使用 {$phone.i.phone} 形式的 smarty 变量显示,其中 i 是电话号码数组中的数组键。

我希望能够使用js更改这些电话号码的格式。

所以对于一个电话号码,我在我的 smarty .tpl 文件中使用了以下内容:

{literal}
cj(function($){

  var phoneNumber = {/literal}{$phone.1.phone}{literal};

  var phoneNumberFormatted = '(' + phoneNumber.substr(0,3) + ') ' + phoneNumber.substr(3,3) + '-' + phoneNumber.substr(6);

  $(".crm-contact_phone span").text(phoneNumberFormatted);

});
{/literal}

所以我想,我需要按照以下方式做一些事情:

$('.crm-contact_phone span').each(function(i, obj) {
    var phoneNumber = '' + {/literal}{$phone.1.phone}{literal};   
}

但我不知道如何将 smarty 变量中的 1 替换为 javascript 索引 i。

有什么想法吗?谢谢。

【问题讨论】:

    标签: javascript jquery smarty


    【解决方案1】:

    试试这个

    $('.crm-contact_phone span').each(function(i, obj) {
          var phoneNumber = '' + {/literal}{$phone[i].phone}{literal}; 
    }
    

    使用 方括号符号 并将其替换为 i

    【讨论】:

      【解决方案2】:

      最后我采取了不同的方法,使用以下方法将整个 smarty 数组保存到一个 js 数组中:

      var phoneNumbers = {/literal}{$phone|@json_encode}{literal};
      

      然后我可以使用纯 js 访问电话号码:

       var phoneNumber = phoneNumbers[i]['phone'];
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-11-28
        • 1970-01-01
        • 2016-12-12
        • 1970-01-01
        • 1970-01-01
        • 2022-06-22
        • 1970-01-01
        相关资源
        最近更新 更多