Javascript 使用 jquery 获取页面中的所有链接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12702511/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
get all the links in a page using jquery
提问by Debjeet Das
I need to get all the links in the page using .each(function(){});
in JQuery
我需要.each(function(){});
在 JQuery 中使用页面中的所有链接
<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>
回答by Eli
$("a").each(function() {
//Do your work
})
回答by bart s
Use the anchor tag as selector
使用锚标签作为选择器
$("a").each(....)
回答by thecodeparadox
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
});
for all a
s, change the selector #mm a
to just a
;
对于所有a
s,将选择器更改#mm a
为 just a
;
回答by Debjeet Das
this is what i expected guys...thanks for ur replies
这就是我所期望的……谢谢你的回复
$("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',"#");
});
});
回答by Aaron Sherman
If you want all the unique links on a page, borrowing from other answers on this page and 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);
}
回答by Preben Huybrechts
You can just do $('a')
this will return a collection of al the A elements on a page.
您可以这样做$('a')
将返回页面上所有 A 元素的集合。
Then you can iterate over it with $('a').each(function(index, value){})
然后你可以迭代它 $('a').each(function(index, value){})