2016-10-12 48 views
1
var downloadLinks = document.querySelectorAll('[href*="/Download"]'); 

給了我所有元素的NodeList,但是如何從所有節點中只提取href作爲單個數組?從Nodelist中提取href

我試圖return Array.from(downloadLinks)但看起來像PhantomJS不支持ES6,所以我得到TypeError: undefined is not a function

+3

你不知道什麼?如何迭代集合?如何閱讀財產?如何製作新陣列?對於擁有數百個JavaScript/jQuery帖子的人來說,這似乎是一項非常簡單的任務。 –

回答

0
Array.prototype.map.call(document.querySelectorAll("[href*="/Download "]"), function (e) { 
    return e.getAttribute('href'); 
}); 
+0

1.您查詢選擇器屬性有點奇怪,2.爲什麼不是'[] .map.call(document.querySelectorAll('[href * =「/ Download」]'),function(e){return e .href;});'? –

3
var downloadLinks = document.querySelectorAll('[href*="/Download"]'); 
var arrHREF = []; // create an Array to save hrefs 
var i = 0; 
for(; i<downloadLinks.length; i++) { 
    arrHREF.push(downloadLinks[i].href); // push hrefs in array 
} 

,或者你可以在一行寫爲(使用宣佈在執行括號變量的for循環屬性)

for (var downloadLinks = document.querySelectorAll('[href*="/Download"]'), arrHREF = [], i = 0; i < downloadLinks.length; i++) arrHREF.push(downloadLinks[i].href); 
+1

呃我應該已經更清楚了。我會以同樣的方式做到這一點,但因爲我一遍又一遍地在做這件事,所以我正在尋找一種有效的方式,理想情況下是一個班輪,而不是一個班次? – 3zzy

+1

@ 3zzy:這就是http://codereview.stackexchange.com的用途。 –

+1

@squint哇,第一次聽說過,現在就來看看吧!謝謝。 – 3zzy