如何使用jQuery在HTML属性中呈现javascript变量

使用以下代码:

如果我有这样的JS变量

 var name = John 

如何使用jQuery在第一个代码片段中用我的JS变量替换“[firstName]”?

如果我需要使用jQuery设置属性,就可以了:

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

只需在你的字符串上运行replace …:

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

PS你确定你想要一个属性addthis:title ,而不仅仅是title ? 这是无效的HTML! 如果要创建自己的属性,请在data-加上:

 

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

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