我有一些數組,從類似的「a」元素收到。jQuery:獲取目標和內容
links = jQuery('a');
如何獲得帶有href目的地和內容的字符串?例如:
<a href="/dest1">First</a>
<a href="/dest2">Second</a>
need =>
/dest1 First, /dest2 Second
我有一些數組,從類似的「a」元素收到。jQuery:獲取目標和內容
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(', ');
.map()
遍歷你匹配的元素;return
用您返回的字符串替換元素(在對象中)。.get()
將返回的jQuery對象轉換爲底層的JS對象,在這種情況下是一個數組。.join()
將部件連接在一起。謝謝,這就是我需要:) –
啊,像你的答案更好。我想知道什麼是將jQuery對象轉換爲數組的最佳方式。 – pjdanfor
獲取第一個鏈接和內容;
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
的各種技術:
「:當量」 僞級
$('a:eq(0)'); //this gets the first anchor. (":nth-child" pseudo-class is "0-indexed", meaning it starts counting from 0)
「:nth-孩子「僞類
$("a:nth-child(1)"); //this also gets the first anchor. (":nth-child" pseudo-class is "1-indexed", meaning it starts counting from 1)
。首先()和的.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()]);
});
我創建了一個小的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;
}
也許看看jQuery的attr和html函數。並在href屬性。 –