2015-02-09 243 views
0

我試圖跟蹤特定鏈接上的點擊次數。但首先我需要測試我的腳本的所有鏈接,無論id。用jQuery跟蹤點擊 - php跟蹤

我這頭標記之間:

<script type='text/javascript' src='//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js'></script> 

身體標記之間的某個地方,我有:

<script type="text/javascript"> 
    $(document).ready(function() { 

    $('a').click(function(e) { 

    // ++++ Not sure what this condition does ++++ 
    if($(this).attr("href").indexOf("http")==1) { 

     //prevent the redirect; 
     e.preventDefault(); 

     //do your tracking 
     $.ajax({ 
      url: 'tracking.php', 
      data: "link=" + $(this).attr("href"), 
      complete: function(){ 
       //now do the redirect 
       window.location = $(this).attr("href"); 
      } 

    }); 
    } 

    }); 


    }); 
    </script> 

只是爲了測試,tracking.php看起來是這樣的:

<?php 
$tckfile = fopen("tracking.txt", "w") or die("Unable to open file!"); 
$txt = "Test" . "\r\n"; 
fwrite($tckfile, $txt); 
fclose($tckfile); 
?> 

我做了更改並重新加載我的頁面,但似乎沒有工作。我發現這個代碼在stackoverflow上,不知道它會起作用。

任何想法?

謝謝!

+0

你能提一下你在哪裏找到它嗎?該條件檢查鏈接在其「href」屬性中包含文本「http」。如果有任何錯誤,請告訴我們。 – 2015-02-09 19:45:32

+2

試試'alert($(this).attr(「href」)。indexOf(「http」));''ifofre' if(){}'block你不明白。 – MonkeyZeus 2015-02-09 19:48:52

+0

請注意,如果您的定位標記看起來像這樣'Contact Us!' – MonkeyZeus 2015-02-09 19:57:20

回答

0

刪除您的indexOf("http"),或不包含http的鏈接無法計數。

<script type="text/javascript"> 
    $(document).ready(function() { 

    $('a').click(function(e) { 
    if($(this).attr("href")){ 
     //prevent the redirect; 
     e.preventDefault(); 

     //do your tracking 
     $.ajax({ 
      url: 'tracking.php', 
      data: "link=" + $(this).attr("href"), 
      complete: function(){ 
       //now do the redirect 
       window.location = $(this).attr("href"); 
      } 

    }); 
    } 

    }); 


    }); 
    </script>