【问题标题】:jQuery / Javascript inserting attributes to an elementjQuery / Javascript向元素插入属性
【发布时间】:2014-11-23 03:16:15
【问题描述】:

好的,我有这个脚本:

$(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);
});

它在一个区域中搜索数字模式并为该数字创建一个链接。 这部分正在工作。但是我试图让它也传递一个“onclick”值,但我无法让它工作?

有什么想法吗?

【问题讨论】:

  • 这是 Google Analytics 的事件跟踪代码。我需要它看起来像onclick="ga('send', 'event', 'lead', 'phone call', 'call');"

标签: javascript jquery regex attr


【解决方案1】:

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

return $('<a>').attr({
            href: "tel:"+v"
        })
        .on('click', function() {ga('send', 'event', 'lead', 'phone call', 'call');})
        .html(v)[0].outerHTML;

**使用.on方法的演示:**

$(function() {
  var myLink = $('<a>')
    .attr('href', '#myLink')
    .on('click', function() {
      alert('Thanks for clicking me. Attach ga handler here');
      // ga(this,'send', 'event', 'lead', 'phone call', 'call');
    })
    .text("Click me");

  $('#insert-link-here').append(myLink);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p>The chaining order matters. jQuery.text() returns String but jQuery.text(string) returns jQuery.</p>

<div id="insert-link-here"></div>

【讨论】:

  • 我的麻烦是我需要使用正则表达式来查找和创建链接,我没有链接 ID
  • @scabbyjoe 您已经在问题中找到了链接。在 attr() 调用之后,只需使用 .on 方法附加一个单击事件处理程序。我可以编辑我的答案以匹配。
  • 很抱歉,您能否编辑您的答案,我无法正常工作。
  • @scabbyjoe 我做了 :-) 再次检查。我添加了一个点击 jquery 处理程序。
  • 非常感谢您的帮助,我仍然无法使用它,它似乎破坏了我的 attr 功能,但还是要感谢您!
猜你喜欢
  • 2012-09-15
  • 2010-09-17
  • 2011-04-17
  • 2013-08-21
  • 1970-01-01
  • 1970-01-01
  • 2018-03-14
  • 2017-05-18
  • 1970-01-01
相关资源
最近更新 更多