【问题标题】:Tracking clicks with jquery - php tracking使用 jquery 跟踪点击 - php 跟踪
【发布时间】:2015-04-09 16:12:02
【问题描述】:

我正在尝试跟踪特定链接的点击次数。但首先我需要为所有链接测试我的脚本,不管 id 是什么。

我在头标签之间有这个:

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

在body标签之间的某个地方,我有:

    <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 上找到了这段代码,但不确定它是否有效。

有什么想法吗?

谢谢!

【问题讨论】:

  • 你能说说你在哪里找到的吗?该条件检查链接是否在其href 属性中包含文本"http"。另外,如果有任何错误,请告诉我们。
  • 在您不理解的 if(){} 块之前尝试 alert($(this).attr("href").indexOf("http"));
  • 请注意,如果您的锚标签看起来像这样&lt;a href="/contact.php"&gt;Contact Us!&lt;/a&gt;,您的代码将失败
  • 我在这里找到了它:stackoverflow.com/questions/17337982/…。我没有看到错误,但我的 php 似乎没有执行。好的,我会尝试警报。我的链接是带有 http 的完整链接,所以它应该可以工作。
  • @monkeyzeus 有趣的是,警报显示 0(零)和一个看起来像这样的链接标签:example.com/subfolder">我的链接 01 - 不知道为什么,因为它包含 http,并且警报显示 -1有一个看起来像这样的链接标签:我的链接02,那是因为它没有http,对吧?谢谢大家

标签: javascript php jquery hyperlink


【解决方案1】:

删除你的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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-13
    • 1970-01-01
    相关资源
    最近更新 更多