如何选择具有特定href的所有锚点?

时间:2011-01-07 20:17:15

标签: jquery html

我有以下代码来跟踪与特定网址匹配的外部链接的网页浏览量。

    $("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']);
            });
        }
    });

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

7 个答案:

答案 0 :(得分:50)

您可以使用Attribute Starts With Selector

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

答案 1 :(得分:12)

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

使用属性选择器,您可以查找特定的href。我使用的href=代替了指定的字符串开头的任何元素。

此外,您无需使用href^=绑定到您将选择的所有锚标记的click事件。 each会自动为您执行此操作。

click()

答案 2 :(得分:2)

在jQuery中获取所有hrefs就像:

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

alert("Found: " + elements.length);

答案 3 :(得分:2)

如果需要获取具有某些特定结尾属性的元素,也可以将属性结束与选择器一起使用。像这样:

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

希望这有助于某人。

答案 4 :(得分: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();
});

答案 5 :(得分: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()

答案 6 :(得分:1)

您可以在这里找到代码:

<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>