使用jquery获取页面中的所有链接

时间:2012-10-03 05:44:51

标签: javascript jquery html

我需要在JQuery中使用.each(function(){});获取页面中的所有链接

<div id="mm">
    <ul class="mg">
        <li id="nav_sports">
            <a href="http://www.google.com" class="atest">Sports</a>
            <div id="sports">
                <ul>
                    <li>
                        <a href="http://www.dictionay.com">cricket</a>
                    </li>
                </ul>
                <ul id="cont1">
                    <li style="color:#444444">
                        <b>Popular</b>
                    </li>
                </ul>
            </div>
        </li>
    </ul>
</div>

6 个答案:

答案 0 :(得分:13)

$("a").each(function() {
    //Do your work   
})

答案 1 :(得分:4)

使用锚标记作为选择器

$("a").each(....)

答案 2 :(得分:4)

var links = [];
$('#mm a').each(function() {
   links.push( this.href ); 
   // output of links: ['http://www.google.com', 'http://www.dictionay.com']
   // According to comment
   // if you need each link separately then
   // may try like

   var href = this.href;
   // now process with the href as you wish      
});

对于所有a,将选择器#mm a更改为a;

答案 3 :(得分:4)

这是我所期待的...感谢您的回复

$("a").attr("clink","");
    $(window).load(function(){
        $("#mm a").attr("clink","");
        $('#mm a').each(function(){
            var hrefl=$(this).attr('href');
            var clink=hrefl;
            $(this).attr('clink',clink);
            $(this).attr('href',"#");
        }); 
});

答案 4 :(得分:3)

如果您想要页面上的所有唯一链接,请借用此页面上的其他答案并Unique values in an array

function onlyUnique(value, index, self)
{
    return self.indexOf(value) === index;
} 

function getAllLinks()
{
   var links = [];
   $("a").each(function ()
   {
      links.push(this.href);
   });

   return links.filter(onlyUnique);
}

答案 5 :(得分:2)

你可以$('a')这将返回页面上A元素的集合。

然后您可以使用$('a').each(function(index, value){})

进行迭代