给定一个 html block ,它是一个 var,而不是在实际文档上:
var html_cmt = "Check out this awesome link: https://github.com/jquery/jquery-ui Check out this awesome link: https://github.com/jquery/jquery-ui Check out this awesome link: https://github.com/jquery/jquery-ui Check out this awesome link:"
我需要构建一个包含所有链接的数组,我有以下链接,但它只是构建第一个链接,而不是全部。
var hrefs = new Array();
hrefs.push( $("<div>").html(html_cmt).find('a').attr('href'));
关于如何创建所有链接的数组的建议,假设 html 内容不在文档中,只是一个 JS var?谢谢
最佳答案
var hrefs = [];
$("<div>").html(html_cmt).find('a').each(function(){
hrefs.push(this.href);
// ^^^^^^^^^ Resolves URLs automatically. See notes
});
另一种方法:
var hrefs = $("<div>").html(html_cmt).find('a').map(function(){
return this.href;
}).toArray();
注释
this.href
将返回完全解析的 UR,$(this).attr('href')
将返回真实属性。
示例(假设http://localhost/dir/test.php
):
this.href == http://localhost/foo.bar
$(this).attr('href') == /foo.bar
this.href == http://localhost/dir/test.php#doo
$(this).attr('href') == #doo
this.href == http://localhost/file.do
$(this).attr('href') == ../file.do
this.href == http://localhost/dir/
$(this).attr('href') == .
关于javascript - 使用 jQuery 查找将 html 中的所有链接推送到数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8842698/