1

我需要使用 jquery 检索当前 html 页面中存在的所有超链接。我怎样才能使用正则表达式来做到这一点?我也可以在javascript中使用集合来存储列表中的所有href吗?

4

6 回答 6

2

您可以使用简单的每个循环:

// For each <a href=""> tag...
$('a').each(function(){
    // Get the url
    var href = $(this).attr('href')
    // alert it or do sth with it
    alert( href ); 
})
于 2012-07-11T09:24:37.547 回答
1

使用 jQuery$('a')将为您完成

遍历所有锚元素

var hrefArr = [];
$('a').each(function(){
  //hrefArr.push($(this).attr('href')); 
  hrefArr.push(this.href); // this would be bit faster then the statement above it
});

由 OP 编辑​​评论,在字符串中查找锚标记包含 html

str = "<div><a href='local1'></a><a href='local2'></a></div>"
var hrefArr = [];
$(str).filter('a').each(function(){
    hrefArr.push(this.href); 
});​
于 2012-07-11T09:23:58.377 回答
0

所有的锚都很容易

$("a").each(function(){
  alert( $(this).attr("href") );
})
于 2012-07-11T09:24:16.083 回答
0

这将为您提供页面上的所有超链接

$('a')

这将为您提供 hpyerlinks 上的 href 集合

var hrefs = new Array();
$('a').each(function() {
    hrefs.push(this.attr('href'));
});
于 2012-07-11T09:24:38.530 回答
0

尝试这个:

var link = "";
$("a").each(function() {
    link += $(this).attr("href"); 
});
alert(link);
于 2012-07-11T09:41:16.963 回答
0

如果通过“javascript 中的集合”你的意思是一个数组,那么你可以这样做:

var hrefs = [];
$("a").each(function() {
    hrefs.push(this.href);
});
// hrefs array now contains all the hrefs

如果您单击链接,回调.each()函数this.href可能会返回完整的 url,即href="test.htm"返回为http://yourdomain/test.htm. 如果您只想要属性中的字面意思,请使用$(this).attr("href").

您不会使用正则表达式来进行这种类型的处理。

于 2012-07-11T09:27:08.833 回答