开发者

Check link by jQuery

There is a block of links,

<div class="links">
<a href="http://google.com">
<a href="http://bing.com">
<a href="http://example.com/section2/">
</div>

They are all placed in the html of http://example.com/.

How do I check each one, is it a link to currently opened site?

Script should give true to http://example.com/an开发者_JS百科ything/else/in/the/url/ and false to all others site.


check out my jQuery plugin $.urlParser at GitHub: https://github.com/Dyvor/jquery/tree/master/plugins/urlParser

You could try the following code:

var current_host = $.urlParser(window.location.toString()).host;
$('div.links a').each(function() {
    if ( current_host == $.urlParser($(this).attr('href')).host ) {
        // the hosts matched ... place your code here
    }
});


Give your DIV an ID to make it a bit easier:

<div id="links">

and then this script will do what you want:

var links = document.getElementById('links').getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
  if (links[i].href.indexOf('http://mysite.com/') === 0) {
    // Yes, this link belongs to your site
    // do something
  } else {
    // do something else
  }
}


this should do it

$("a").each(function(){
  return $(this).attr("href").indexOf("http://mysite.com")==0;
});

Another way

$("a[href^='http://mysite.com/']")

will only give you the links you need

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜