我正在尝试使用下面这样的Facebook转换代码,其中包括
脚本和noscripts标签:
<html>
<head>
<script type="text/javascript">
// Wait for the page to load first
window.onload = function() {
//Get a reference to the link on the page
// with an id of "mylink"
var a = document.getElementById("mylink");
//Set code to run when the link is clicked
// by assigning a function to "onclick"
a.onclick = function() {
// Code to be executed when the link is clicked.
var _fbq = window._fbq || (window._fbq = []);
...
}
}
</script>
<noscript><img height="1" width="1" alt="" style="display:none" src="https://www.facebook.com/tr?ev=6030151253043&cd[value]=0.00&cd[currency]=USD&noscript=1" /></noscript>
</head>
<body>
<a id="mylink" href="http://example.com">Link</a>
</body>
</html>
通常我可以把这个代码放在我网站的感谢页面上。但现在我有一种情况,如果有人点击了一个外部链接,导致某个外部网页超出了我的控制范围,我想跟踪这种情况。我的页面在加载时不应执行此转换代码,而应仅在单击链接时执行。
例如,我的页面有一个链接,指向http://example.com,因此当用户单击此链接时,可以执行此转换代码,然后转到http://example.com?
问题是,当浏览器不支持JavaScript时,即使没有单击链接,noscript标记内的代码也会执行。
有什么办法解决那个问题吗?
您尝试过使用JavaScript onclick事件吗?例如:
var el; // This is your element pointing to the link you want to handle
el.onclick = function() {
// Execute your code here, this event is fired before the default behaviour is executed which is to lead the user to the URL
};
如果你的el有一个mylink的ID,那么你可以简单地将el指定为
var el = document.getElementById('mylink');
如果您使用的是像jQuery这样的JS库,那么这段代码会变得更容易处理,但目前我认为您不是。
以下是关于如何使用链接调用JavaScript的答案的编辑版本?
// Wait for the page to load first
window.onload = function() {
//Get a reference to the link on the page
// with an id of "mylink"
var a = document.getElementById("mylink");
//Set code to run when the link is clicked
// by assigning a function to "onclick"
a.onclick = function() {
// Your code here...
//If you don't want the link to actually
// redirect the browser to another page,
// "google.com" in our example here, then
// return false at the end of this block.
// Note that this also prevents event bubbling,
// which is probably what we want here, but won't
// always be the case.
return false;
}
}
</script>
<noscript><img height="1" width="1" alt="" style="display:none" src="https://www.facebook.com/tr?ev=6030151253043&cd[value]=0.00&cd[currency]=USD&noscript=1" /></noscript>
</head>
<body>
<a id="mylink" href="http://example.com">Link</a>
</body>
</html>
只有当浏览器不支持JavaScript时,才会使用noscript标记。这就是为什么你不打算在那里放任何JavaScript。
是的,你可以做到。
放入链接href="javascript:void(0)"并使用javascript重定向。
<a href="javascript:void(0)" onClick="do_and_redirect()">Your link</a>
<script>
function do_and_redirect(){
//SOME CODE
//..
//..
window.location.href = "http://yourpage.com";
}
</script>