开发者

How to render a javascript variable in an HTML attribute using jQuery

开发者 https://www.devze.com 2023-04-06 14:25 出处:网络
Using the following code: <div class=\"whatever\" addthis:title=\"Hi, your name is [firstName]\"></div>

Using the following code:

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

If I have a JS variable like this

var name = John

How would I replace开发者_JS百科 the "[firstName]" with my JS variable in the first code snippet using jQuery?

It's ok if I need to set the attribute using jQuery to begin with like:

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


Simply run replace on your string...:

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

P.S. Are you sure you want an attribute addthis:title, not simply title? That's invalid HTML! If you want to create your own attributes, prefix them with data-:

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


Did you try it? Your example code contains all the pieces you need.

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

精彩评论

暂无评论...
验证码 换一张
取 消