javascript - 使用 jQuery 查找将 html 中的所有链接推送到数组?

标签 javascript jquery

给定一个 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/

相关文章:

javascript - 使用 ajax 读取 XML 节点

javascript - ng如果不更新 DOM

javascript - 将 MATLAB 连接到 Firebase 数据库

javascript - 删除链式 promise

javascript - MVC Controller 方法不是从 ajax 调用的

javascript - jquery 输入 - 如何正确处理文本更改

javascript - 通过可点击的链接传递撇号或双引号时遇到问题

javascript - 检查 Google 云端硬盘文件夹中的文件是否已存在且超过一定大小

javascript - jQuery 检查 Android 原生浏览器或 Chrome

php - 中文文本插入数据库后变得不可读?