Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/377.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/83.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/Javascript向元素插入属性_Javascript_Jquery_Regex_Attr - Fatal编程技术网

jQuery/Javascript向元素插入属性

jQuery/Javascript向元素插入属性,javascript,jquery,regex,attr,Javascript,Jquery,Regex,Attr,好的,我有这个脚本: $(document).ready(function () { var content = $(".main").html(); content = content.replace(/\d{3}-\d{3}-\d{4}/g, function(v){ return $('<a>').attr({ href: "tel:"+v, onclick: "ga('send', 'event'

好的,我有这个脚本:

$(document).ready(function () {
    var content = $(".main").html();
    content = content.replace(/\d{3}-\d{3}-\d{4}/g, function(v){
        return $('<a>').attr({
            href: "tel:"+v,
            onclick: "ga('send', 'event', 'lead', 'phone call', 'call');"
        }).html(v)[0].outerHTML;
    });

    $('.main').html(content);
});
$(文档).ready(函数(){
var content=$(“.main”).html();
content=content.replace(/\d{3}-\d{3}-\d{4}/g,函数(v){
返回$('').attr({
href:“电话:”+v,
onclick:“ga('send'、'event'、'lead'、'phone call'、'call')
}).html(v)[0].outerHTML;
});
$('.main').html(内容);
});
它在区域中搜索数字模式,并为数字创建链接。 这部分工作正常。然而,我试图让它也通过一个“onclick”值,但我不能让它工作


有什么想法吗?

您也可以尝试使用jQuery的on方法将处理程序附加到click事件,如果这不会破坏跟踪:

return $('<a>').attr({
            href: "tel:"+v"
        })
        .on('click', function() {ga('send', 'event', 'lead', 'phone call', 'call');})
        .html(v)[0].outerHTML;
return$('').attr({
href:“电话:“+v”
})
.on('click',function(){ga('send','event','lead','phone call','call');})
.html(v)[0].outerHTML;
**使用.on方法演示:**
$(函数(){
变量myLink=$('')
.attr('href','myLink'))
.on('单击',函数()){
警报('谢谢单击我。在此处附加ga处理程序');
//ga(此、'send'、'event'、'lead'、'phone call'、'call');
})
.text(“单击我”);
$(“#在此处插入链接”).append(myLink);
});

链接顺序很重要。jQuery.text()返回字符串,但jQuery.text(字符串)返回jQuery


这是谷歌分析的事件跟踪代码。我需要它看起来像
onclick=“ga('send'、'event'、'lead'、'phone call'、'call');“
我的问题是我需要使用正则表达式来查找和创建链接,我没有链接ID”s@scabbyjoe您的问题中已经有链接。在attr()之后调用时,只需使用.on方法附加一个单击事件处理程序。我可以编辑我的答案以匹配。很抱歉,您是否可以编辑您的答案,我无法使其工作。@scabbyjoe我做了:-)再次检查。我添加了一个单击jquery处理程序。非常感谢您的帮助,我仍然无法使其工作,它似乎破坏了我的attr函数,但比k你非少!