我想解析文档中的所有HTML,如果有PDF链接,请添加onClick事件。
示例:
<a href="/files/report.pdf">Report</a>
变为:
<a href="/files/report.pdf" onclick="javascript: _gaq.push(['_trackPageview', '/files/report.pdf']);">Report</a>
以下代码适用于Chrome / Firefox,但不适用于IE9:
function AddGaqPush()
{
var links = document.getElementsByTagName("a");
for (var i=0; i < links.length; i++)
{
if (links[i].href.indexOf(".pdf") !== -1)
{
links[i].setAttribute("onclick", "javascript: _gaq.push(['_trackPageview', '" + links[i].href + "']);");
}
}
}
编辑添加:IE设置:浏览器模式:IE9;文档模式:IE9标准
答案 0 :(得分:4)
使用jQuery,您不会受到浏览器(尤其是IE)的限制
$('a[href~=.pdf]').click(function(e) {
// your click action
// e is a jQuery event
// your <a> element is the variable this
});
答案 1 :(得分:3)
不添加属性,而是附加事件处理程序
if (links[i].attachEvent){
links[i].attachEvent('onclick', tpv);
}
else{
links[i].addEventListener('click', tpv);
}
function tpv(){
_gaq.push(['_trackPageview', '" + this.href + "']);
}
答案 2 :(得分:2)
完成此任务的jQuery语句如下所示:
$('a[href*=".pdf"]').click(function(e) {
_gaq.push(['_trackPageview', $(this).attr('href')]);
});
我喜欢Nannuo Lei对这个问题的回答,但解决方案并不完全准确/完整,而且我还没有足够的声誉对该帖子发表评论。
您将需要围绕要搜索的字符串的引号,* =选择器允许您识别较大字符串的子字符串,而不仅仅是由〜=选择器将完成的由空格分隔的单词。有关jQuery选择器的更多详细信息,请访问:https://api.jquery.com/category/selectors/