2010-10-02 52 views

回答

2
var linkcheck = (function(){ 
    if(!Array.indexOf){ 
    Array.prototype.indexOf = function(obj){ 
    for(var i=0; i<this.length; i++){ 
    if(this[i]===obj){ 
     return i; 
    } 
    } 
     return -1; 
    } 
    } 
    var url_pages = [], anchor_nodes = []; // this is where you put the resulting urls 
    var anchors = document.links; // your anchor collection 
    var i = anchors.length; 
    while (i--){ 
    var a = anchors[i]; 
    anchor_nodes.push(a); // push the node object in case that needs to change 
    url_pages.push(a.href); // push the href attribute to the array of hrefs 
    } 
    return { 
    urlsOnPage: url_pages, 
    anchorTags: anchor_nodes, 
    checkDuplicateUrls: function(url_list){ 
     var duplicates = []; // instantiate a blank array 
     var j = url_list.length; 
     while(j--){ 
     var x = url_list[j]; 
     if (url_pages.indexOf(x) > -1){ // check the index of each item in the array. 
      duplicates.push(x); // add it to the list of duplicate urls 
     } 
     } 
     return duplicates; // return the list of duplicates. 
    }, 
    getAnchorsForUrl: function(url){ 
     return anchor_nodes[url_pages.indexOf(url)]; 
    } 
    } 
})() 
// to use it: 
var result = linkcheck.checkDuplicateUrls(your_array_of_urls); 

这是一个相当简单的实施纯JavaScript方法实现什么,我相信对于规范要求的。这也封使用,给你访问结果集在任何时间,以防您的网址列表的变化随着时间的推移,需要检查新的列表。我还将结果标签添加为一个数组,因为我们正在迭代它们,因此您可以随时更改它们的属性。而且,因为通过传递url(结果集中的第一个)来获取锚点标记有一个方便的方法可能会很有用。每下面的评论,包括片段创建IE8的indexOf和切换document.getElementsByTagName到document.links获得对象的动态列表。

+1

注意* Array.prototype.indexOf()*没有在IE 8及以上的实施,将需要额外的片段界定方法。还要注意你的列表是静态的。您可以使用* document.links *在页面上获取* A *和* AREA *元素的动态集合。 – 2010-10-02 22:55:04

+0

@安迪E感谢您的信息。我认为indexOf的实现无处不在。最近我一直在使用jQuery,我完全分开了document.links。 – Gabriel 2010-10-03 01:47:54

10

getElementByTagName为您提供了一个nodelist(节点数组)。

var a = document.getElementsByTagName('a'); 

for (var idx= 0; idx < a.length; ++idx){ 
    console.log(a[idx].href); 
} 

我真的建议你为此使用框架工作,如jQuery。它让你的生活变得如此简单。

示例使用jQuery:

$("a").each(function(){ 
    console.log(this.href); 
}); 
+1

这是非常简单的,虽然 - 会真的使用jQuery是更容易?我认为它可能实际上需要更多的字符是'$()。attr('blahblah')等。 – 2010-10-02 07:31:32

+1

@Mark:我添加了一个jQuery的例子。正如你所看到的那样,输入更少。 – some 2010-10-02 07:42:33

-1

使用jQueryü可以做一些事情像这个 -

$('a').each(function(){ 
if(urls.indexOf(this.href) !- -1) 
    alert('match found - ' + this.href); 
}) 

网址是需要用比较现有的阵列。

相关问题