Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/398.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用jQuery在HTML属性中呈现javascript变量_Javascript_Jquery_Variables_Attributes - Fatal编程技术网

如何使用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);