2017-09-26 62 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)。通過事件跟蹤,您可以將分析提醒到自定義事件,然後在分析儀表板,你可以根據他們創建目標,我會用一個註釋過的例子更新我的代碼,並且接受我的回答,這樣我就可以提高我的聲譽!:) –