2014-09-28 55 views
0

好了,所以我有這樣的腳本:的jQuery/JavaScript的插入屬性的元素

$(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」的價值,但我不能得到它的工作?

任何想法?

+0

什麼是'ga' ..? – 2014-09-28 18:08:22

+0

這是Google Analytics的事件跟蹤代碼。 我需要它看起來像'onclick =「ga('send','event','lead','phone call','call');'' – scabbyjoe 2014-09-28 18:12:32

回答

0

你也可以嘗試使用jQuery的方法上的處理程序附加到Click事件是否會不會打破追蹤:

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

**演示使用。對方法:**

$(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>

+0

我的麻煩在於我需要使用Regex來找到並創建鏈接,我沒有鏈接ID的 – scabbyjoe 2014-09-28 18:30:28

+0

@scabbyjoe你已經有你的問題的鏈接。在attr()調用之後,只需使用.on方法附加一個單擊事件處理程序。我可以編輯我的答案來匹配。 – leon 2014-09-28 18:33:07

+0

我很抱歉,但你可能編輯你的答案,我沒有得到這個工作。 – scabbyjoe 2014-09-28 18:47:50