如何使用jQuery在HTML属性中呈现javascript变量
使用以下代码:如何使用jQuery在HTML属性中呈现javascript变量,javascript,jquery,variables,attributes,Javascript,Jquery,Variables,Attributes,使用以下代码: <div class="whatever" addthis:title="Hi, your name is [firstName]"></div> 在使用jQuery的第一个代码段中,如何用我的JS变量替换“[firstName]” 如果我需要使用jQuery设置属性,可以这样开始: $('.whatever').attr( 'addthis:title', 'Hi, your name is [firstName].' ); 只需在字符串上运行rep
<div class="whatever" addthis:title="Hi, your name is [firstName]"></div>
在使用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);
});
另外,您确定要添加一个属性addthis:title
,而不仅仅是title
?那是无效的HTML!如果要创建自己的属性,请在其前面加上数据-
:
<div class="whatever" data-addthis-title="Hi, your name is [firstName]"></div>
你试过了吗?您的示例代码包含您需要的所有部分
var name = "John";
var element = $('.whatever');
var newAttrValue = element.attr('addthis:title').replace(/\[firstName\]/, name);
element.attr('addthis:title', newAttrValue);
工作完美。关于无效属性,“添加此”社交插件正在使用它。
var name = "John";
var element = $('.whatever');
var newAttrValue = element.attr('addthis:title').replace(/\[firstName\]/, name);
element.attr('addthis:title', newAttrValue);