【问题标题】:Grab the href and text of <a> tags from the page从页面中获取 <a> 标签的 href 和 text
【发布时间】:2015-08-11 19:36:30
【问题描述】:

我有一个包含多个链接的页面(&lt;a&gt; 带有特定类选择器的标签,例如 "class=my-link"),我需要获取这些链接的文本(&lt;a&gt; 和 &lt;/a&gt; 标签之间的内容)以及它们的"href" 属性并将其输出到一个JavaScript 多维对象中,并给出一个ID 号(只是递增,01、02、03 等等)。

示例。

带有链接的原始页面:

<a href="red" class="my-link">Apples are red</a>
<a href="green" class="my-link">Grass is green</a>

输出:

var mylinks = [
  { "LinkID": "01", "LinkHref": "red", "LinkText": "Apples are red" },
  { "LinkID": "02", "LinkHref": "green", "LinkText": "Grass is green" }
];

【问题讨论】:

标签: javascript jquery html object


【解决方案1】:

您可以执行以下操作

var arr = [];
$.each( $("a.my-link"), function( i, element ) { // iterate over all anchor elements with class my-link
   arr.push({
       "LinkID" : i+1,
       "LinkHref" : $(element).attr("href"),
       "LinkText" : $(element).html()
   });
});

【讨论】:

    猜你喜欢
    • 2010-10-27
    • 2021-12-26
    • 2017-06-04
    • 2015-12-04
    • 1970-01-01
    • 2013-03-04
    • 2018-05-14
    • 2013-07-07
    相关资源
    最近更新 更多