2017-09-26 61 views
-3

默认情况下,试图隐藏电话号码,迫使用户“点击揭示”。除此之外,添加相关事件跟踪功能,以便我们可以使用Google Analytics事件跟踪跟踪点击次数。jquery显示点击字符串(tel :)

我试过这个脚本:

$(document).ready(function() { 
    var phonenumbers = []; 
    $(".phonenumber").each(function(i) { 
     phonenumbers.push($(this).text()); 
     var newcontent = $(this).text().substr(0, $(this).text().length - 4) 
     $(this).text(newcontent); 
     $(this).bind("click", function() { 
      if ($(this).text() == phonenumbers[i]) { 
       $(this).text(phonenumbers[i].substr(0, phonenumbers[i].length - 4)); 
      } else { 
      $(".phonenumber").each(function(x) { 
       if ($(this).text() == phonenumbers[x]) { 
        $(this).text(phonenumbers[x].substr(0, phonenumbers[x].length - 4)); 
       } 
      });    
      $(this).text(phonenumbers[i]); 
      } 
     }); 
    }); 
}); 

通过使用这种格式默认隐藏的最后4位数字:

<a class="phone" href="tel:04480252578">044 802 52578</a>

但我还想使用完全不同的锚文本,隐藏整个电话号码,直到点击新的定位文字。

+3

你付多少钱? – Alex

+0

jQuery + ajax调用获取号码和跟踪计数 – Camille

+0

感谢您分享您尝试过的代码。当你来这里寻求帮助时,这就是人们正在寻找的东西。否则,你的问题将被放弃投票。 –

回答

1

您不需要AJAX进行跟踪;如果您尝试使用Google Analytics(分析)之类的功能进行跟踪,则只需点击揭示内容即可在分析中触发事件。

有几种方法可以做到这一点,有些人可能会试图隐藏电话号码后面的绝对定位元素,说“揭示”。我选择仅使用href来获取数字并替换元素的文本。

$(document).ready(function(){ 

     // Use one instead of on so that you're only preventing default once 
     $('a[href^="tel:"]').one('click', function(e){ 

      e.preventDefault(); 

      // Gets the string from the href and removes anything not a digit 
      var phone_number = $(this).attr('href').replace(/\D/g,''); 

      // 044 802 52578 
      var phone_formatted = phone_number.substr(0, 3); 
      phone_formatted += ' ' + phone_number.substr(3, 3); 
      phone_formatted += ' ' + phone_number.substr(6); 

      // Trigger your analytics event 
      // ga is used by Google Analytics, 
      // it must be loaded before you do this 
      ga('send', { 
       hitType: 'event', 
       eventCategory: 'Interaction', 
       eventAction: 'click-reveal-phone',  
       eventLabel: 'Phone Number Revealed', 
       eventValue: 0, 
       nonInteraction: true 
      }); 
      // The above could be written like this as well 
      // ga('send', 'event', 'Interaction', 'click-reveal-phone', 'Phone Number Revealed'); 


      $(this).text(phone_formatted); 

    }) 

}) 

Here is a jsFiddle

+0

非常感谢这段代码,我实际上已经使用wordpress删除了$(document).ready(function(){而不是使用 jQuery(document).ready(function($){ 我需要:)感谢你的时间 – Randomer11

+0

出于兴趣,您已评论//触发您的分析事件。是否还需要其他代码? – Randomer11

+0

是的,那只是我根据对原始问题的评论而投入的内容。如果您正在使用Google Analytics(分析),请查看事件跟踪(https://developers.google.com/analytics/devguides/collection/analyticsjs/events)。通过事件跟踪,您可以将分析提醒到自定义事件,然后在分析仪表板,你可以根据他们创建目标,我会用一个注释过的例子更新我的代码,并且接受我的回答,这样我就可以提高我的声誉!:) –