I have a page with multiple links (<a>
tag with a specific class-selector, e.g. "class=my-link"
), I need to grab the text of these links (the content between <a>
and </a>
tags) and their "href"
attribute and output it into a JavaScript multidimensional object, giving an ID number (just increment, 01, 02, 03 and so on).
Example.
Original page with links:
<a href="red" class="my-link">Apples are red</a>
<a href="green" class="my-link">Grass is green</a>
Output:
var mylinks = [
{ "LinkID": "01", "LinkHref": "red", "LinkText": "Apples are red" },
{ "LinkID": "02", "LinkHref": "green", "LinkText": "Grass is green" }
];
答案 0 :(得分:2)
您可以执行以下操作
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()
});
});