我正试图跟踪特定链接的点击次数。但首先我需要为所有链接测试我的脚本,无论id如何。
我在头标签之间有这个:
<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上找到了这个代码,不确定它是否有效。
有什么想法吗?
谢谢!
删除您的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>