【问题标题】:How to render a javascript variable in an HTML attribute using jQuery如何使用 jQuery 在 HTML 属性中呈现 javascript 变量
【发布时间】:2011-09-20 05:02:16
【问题描述】:

使用以下代码:

<div class="whatever" addthis:title="Hi, your name is [firstName]"></div>

如果我有这样的 JS 变量

var name = John

如何使用 jQuery 在第一个代码 sn-p 中将“[firstName]”替换为我的 JS 变量?

如果我需要使用jQuery设置属性以like开头也可以:

$('.whatever').attr( 'addthis:title', 'Hi, your name is [firstName].' );

【问题讨论】:

    标签: javascript jquery variables attributes


    【解决方案1】:

    只需在您的字符串上运行replace...:

    var name = 'John';
    $('.whatever').attr('addthis:title', function(i, attr){
        return attr.replace('[firstName]', name);
    });
    

    附:您确定要属性addthis:title,而不仅仅是title?那是无效的 HTML!如果您想创建自己的属性,请在它们前面加上 data-:

    <div class="whatever" data-addthis-title="Hi, your name is [firstName]"></div>
    

    【讨论】:

    • 完美运行。关于无效属性,“Add This”社交插件正在使用它。
    【解决方案2】:

    你试过了吗?您的示例代码包含您需要的所有部分。

    var name = "John";
    var element = $('.whatever');
    var newAttrValue = element.attr('addthis:title').replace(/\[firstName\]/, name);
    element.attr('addthis:title', newAttrValue);
    

    【讨论】:

      猜你喜欢
      • 2019-12-26
      • 1970-01-01
      • 1970-01-01
      • 2014-03-05
      • 2013-02-18
      • 1970-01-01
      • 2017-05-19
      • 2021-03-27
      相关资源
      最近更新 更多