开发者

How do I select all anchors with a specific href?

I've got the following code to track pageviews for external links matching a particular URL.

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

This code wor开发者_JS百科ks, but it's extremely inefficient for pages with a lot of links. Is there a way to use a selector to select all the anchors with matching hrefs instead of scanning through all the links on the page?


You can use the Attribute Starts With Selector

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


Yes

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

Using the attribute selector you can look for a particular href. Instead of the normal href= you might expect, I have used href^= which matches any element which starts with the specified string.

Also you do not need to use each to bind to the click event of all the anchor tags you will select. click() will automatically do this for you.

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


In jQuery getting all hrefs would be like:

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

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


You can use attribute ends with selector as well if you need to get elements with some specific ending attribute. Something like this:

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

Hope this helps someone.


Another Simple way is:

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

Gives the list of all the anchor tags in the current page. To get the anchor tags in a div ID you can use:

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

To get the size use:

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


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


Here you can the code:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜