最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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 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].' );

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 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].' );
Share Improve this question asked Sep 20, 2011 at 5:02 saysay 2,6557 gold badges36 silver badges48 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

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)

  1. 暂无评论