2011-01-07 55 views
13

我有以下代码来跟踪与特定网址匹配的外部链接的浏览量。如何选择具有特定href的所有锚点?

$("a").each(function(i){ 
     if (
      $(this).attr('href') == "http://example.com/external/link/" || 
      $(this).attr('href') == "http://example.com/external/link" 
     ) { 
      $(this).click(function(){ 
       _gaq.push(['_trackPageview', '/external/pagename']); 
      }); 
     } 
    }); 

此代码有效,但对于包含大量链接的页面而言效率极低。有没有办法使用选择器来选择所有具有匹配hrefs的锚,而不是扫描页面上的所有链接?

回答

46

可以使用Attribute Starts With Selector

$('a[href^="http://example.com/external/link"]').click(function() { 
     _gaq.push(['_trackPageview', '/external/pagename']); 
}); 
+0

这是如何完成的!您可以将其与[Google Analytics插件]结合使用(http://writeless.se/2011/01/a-no-fuzz-asynchronous-google-analytics-plugin/) – mekwall 2011-01-07 21:26:33

10

$('a[href^="http://example.com/external/link"]').click(function() {}); 

使用属性选择器,你可以找一个特定href。您可能期望使用href^=来代替正常href=,它与开头的任何元素匹配指定的字符串。

此外,您不需要使用each绑定到您将选择的所有锚点标记的点击事件。 click()会自动为你做这个。

$("a[href^="http://example.com/external/link"]").click(function(){ 
    _gaq.push(['_trackPageview', '/external/pagename']); 
}); 
2

在jQuery中获取所有的HREF会是这样:

var href = 'http://www.google.com'; 
var elements = $('a[href=' + href + ']'); 

alert("Found: " + elements.length); 
1
$('a[href^="http://example.com/external/link"]').click(function(e){ 
    // you do want to track which link was clicked, yes? 
    _gaq.push(['_trackPageview', $(this).attr('href') ]); 
    // suppress default click or you'll leave the page immediately: 
    e.preventDefault(); 
    do_other_stuff_presumably_with_gaq(); 
}); 
+0

attr('href')of链接是已知的,我只是想跟踪它是否被点击。我不明白为什么使用preventDefault()。该链接仍应点击外部网址。 – Jazzerus 2011-01-07 20:26:53

+0

您正在将链接信息添加到_gaq数组,然后做什么?如果您立即被带到链接目的地,_gaq []将会丢失,除非您打开新窗口中的链接。 – 2011-01-07 20:29:10

2

您可以使用属性与选择,以及是否需要结束获取具有特定结束属性的元素。像这样的东西:

$('a[href$=your text]') == "your text" 

希望这可以帮助别人。

1

另一种简单的方法是:

$('a[href="MY_ANCHOR_TEXT_HERE"]'); 

给出当前页面中的所有锚标签的列表。 要获得锚标记的DIV ID,您可以使用:

$('#MY_DIV_ID a[href="MY_ANCHOR_TEXT_HERE"]') 

为了获得规模应用:

$('#MY_DIV_ID a[href="MY_ANCHOR_TEXT_HERE"]').size() 
0

在这里,你可以将代码:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
     <script> 
     $(document).ready(function(){ 
     $("a").each(function(){ 
    if($(this).attr("href") == "http://example.com/external/link/") 
    { 
     $(this).hide(); 
    } 
}); 
}); 
</script> 


<a href="http://example.com/external/link/">a website link</a> 
相关问题