简体   繁体   English

获取HTML部分中每个链接的href属性

[英]Get the href attribute for each link in a section of HTML

I've written the following jQuery to loop through each of the <a> objects in a section of HTML: 我编写了以下jQuery,以遍历HTML部分中的每个<a>对象:

$(".chapterindex" + key + " div.link a").each(function(intIndex){
  alert("Numbered index: " + intIndex);
});
});

The key value used in the first line of the jQuery is from an array of URL's I've built manually, something like this: jQuery第一行中使用的键值来自我手动构建的URL数组,如下所示:

var chapters = new Array();
chapters[0] = "original/html/0/ID0EFJAE.html";

I can alert the intIndex which gives me, 0,1,2,3,4,5.... etc.. 我可以提醒intIndex给我0,1,2,3,4,5....等。

But how can I extend the jQuery above to get the href attribute from each of the links found in the HTML? 但是如何扩展上面的jQuery,以从HTML中找到的每个链接中获取href属性?

Try this: 尝试这个:

$(".chapterindex" + key + " div.link a").each(

    function(intIndex){
        alert( "Numbered index: " + intIndex );

        var href = $(this).attr('href');
    });
});

您可以通过$(this).attr('href')访问它

$(".chapterindex" + key + " div.link a").each(

    function(intIndex){
        alert( "Numbered index: " + $(this).attr("href") );
    });
});
$(".chapterindex" + key + " div.link a").each(function () {
  alert(this.href);
});

Do you want the full HREF or the HREF as it appears in the tag? 您是否需要完整的HREF或标签中显示的HREF?

The jQuery object method $(this).attr('href') proposed by some people will return whatever is set as the HREF attribute in the tag. 有人提出的jQuery对象方法$(this).attr('href')将返回标记中设置为HREF属性的任何内容。

The DOM node property method this.href proposed by John will return the fully-qualified URL. John提出的DOM节点属性方法this.href将返回完全限定的URL。

So given a link <a href="/resources/foo.ext">Foo</a> , the jQuery method will return "/resources/foo.ext" while the other method will return "http://mysite.ca/currentpath/resources/foo.ext". 因此,给定链接<a href="/resources/foo.ext">Foo</a> ,jQuery方法将返回“ /resources/foo.ext”,而另一个方法将返回“ http://mysite.ca” /currentpath/resources/foo.ext”。

So it just depends on what you need returned. 因此,这仅取决于您需要退货的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM