2011-03-02 29 views
0
鏈接

有一個鏈接塊,檢查的jQuery

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

它們都放置在http://example.com/的HTML。

我如何檢查每一個,它是一個鏈接到當前打開的網站?

腳本應該對http://example.com/anything/else/in/the/url/賦予真實性,並且對所有其他網站都爲false。

+0

你是什麼意思與'當前打開的網站'?用戶目前在標籤中打開了哪一個? – pimvdb

+0

相同的域名?同一個子域?同一個目錄? http + https? – zzzzBov

+0

同域名,http只有 – James

回答

2

在GitHub上看看我的jQuery插件$ .urlParser鏈接:https://github.com/Dyvor/jquery/tree/master/plugins/urlParser

你可以試試下面的代碼:

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 
    } 
}); 
1

給你的DIV的ID,使其更容易一點:

<div id="links"> 

,然後這個腳本會做你想要什麼:

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

這應該這樣做

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

另一種方式

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

只會給你你需要