2010-04-01 38 views
0

我發現.attr()僅適用於頁面上第一個匹配的元素!所以,我一直試圖從頁面上的所有匹配元素中獲取hrefs,但無濟於事。Jquery:從頁面上的多個鏈接提取hrefs

這裏就是我試探着說:

var thelinks = $("td a").each(function(){ 
    $(this).attr("href"); 
    document.write(thelinks); 
}); 

我用文件撰寫只是爲了看看發生了什麼事情,我得到了「undefinedundefinedundefined」

我試圖以一個長長的清單是從每個td a中提取hrefs,然後使用ajax訪問這些頁面並執行其他操作。當它只處理一個鏈接時,我可以很好地工作,但我無法弄清這個多元素的東西。

任何幫助呈現的讚賞,我是JavaScript和JQuery的世界的新手。

回答

3

更改您的代碼

var thelinks = $("td a").map(function(){ 
    return $(this).attr("href");}); 

document.write(thelinks); 

你想打印出定義它的匿名函數內部「thelinks」的內容。

1

你可以簡化這個這個,你有一些額外的代碼,你的變量沒有正確定義:

$("td a").each(function(){ 
    document.write($(this).attr("href")); 
}); 
2

您的代碼是沒有意義的;首先,each沒有有用的返回值(您想要map代替),其次,您在打印thelinks之前已爲其分配任何值。

也許你希望是這樣的:

var thelinks = $("td a").map(function() { 
    return $(this).attr("href"); 
}).get(); 

// Just for example purposes 
document.write(thelinks.join(", ")); 
0

$( 「TD一」)地圖(函數(){返回this.href})