我有一些数组,来自类似的“a”元素。
links = jQuery('a');
如何获取带有 href 目标和内容的字符串?就像是:
<a href="/dest1">First</a>
<a href="/dest2">Second</a>
need =>
/dest1 First, /dest2 Second
我有一些数组,来自类似的“a”元素。
links = jQuery('a');
如何获取带有 href 目标和内容的字符串?就像是:
<a href="/dest1">First</a>
<a href="/dest2">Second</a>
need =>
/dest1 First, /dest2 Second
您可以使用map()
和join()
:
$('a').map(function(index, link) {
return link.href + ' ' + $(link).text();
// return [link.href, $(link).text()].join(' '); // This works too
}).get().join(', ');
演示:http: //jsfiddle.net/t4nr5/
.map()
迭代匹配的元素;return
将元素替换为您返回的字符串(在对象中)。.get()
将返回的 jQuery 对象转换为底层的 JS 对象,在本例中是一个数组。.join()
将零件连接在一起。我创建了一个小 jsFiddle 来演示你将如何做到这一点,你可以在这里查看它的实际效果:http: //jsfiddle.net/tUY5K/
这是完成工作的方法:
function anathem() {
var links = $('a');
var anathemString = "";
links.each(function (index) {
anathemString += $(this).attr('href') + " " + $(this).html();
if (index != links.length - 1) {
anathemString += ", ";
}
});
return anathemString;
}
首先获取链接和内容;
var first_link = $('a:eq(0)').attr('href'); //first link
var first_content_text = $('a:eq(0)').text(); //content of first anchor element
var first_content_html = $('a:eq(0)').html(); //content of first anchor element including markup
获取第二个链接和内容:
var second_link = $('a:eq(1)').attr('href'); //second link
var second_content_text = $('a:eq(1)').text(); //content of second anchor element
var second_content_html = $('a:eq(1)').html(); //content of second anchor element including markup
各种技巧:
":eq" 伪类
$('a:eq(0)'); //this gets the first anchor. (":nth-child" pseudo-class is "0-indexed", meaning it starts counting from 0)
":nth-child" 伪类
$("a:nth-child(1)"); //this also gets the first anchor. (":nth-child" pseudo-class is "1-indexed", meaning it starts counting from 1)
.first() 和 .next() 方法
$("a").first(); //gets the first anchor element
$("a").first().next(); //gets the second anchor element
获取底层 DOM 元素
$('a').get(0); //This gets the first element in the anchor node list
$('a')[0]; //This also does the same but cannot specify a negative index
试试这个:
var hrefs_array = $.map($('a'), function(el) { return [$(el).attr("href"), $(el).text()];})
或类似的东西
var hrefs_array = [];
$('a').each(function(index, el){
hrefs_array.push([$(el).attr("href"), $(el).text()]);
});