$( "ul.foundData li.id" ).each(function(index) {
var allRelevantData = (index + ": " + $(this).text());
});
我现在将它全部输出到控制台,但我想从迭代输出中创建一个可用的数组。
答案 0 :(得分:5)
使用map()
基于迭代元素创建数组
var data = $( "ul.foundData li.id" ).map(function(index) {
return index + ": " + $(this).text();
}).get();
console.log(data)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="foundData">
<li class="id">Item 1</li>
<li class="id">Item 2</li>
<li class="id">Item 3</li>
<li class="id">Item 4</li>
<li class="id">Item 5</li>
</ul>
&#13;
答案 1 :(得分:1)
就像:
var allRelevantData = [];
$('ul.foundData li.id').each(function(i, e){
allRelevantData.push($(e).text());
});
console.log(allRelevantData[0]); // first index
console.log(allRelevantData); // entire Array
答案 2 :(得分:1)
不确定您对usable array outside iteration output
的意思。
但如果您想获取文字内容并且&#34;保存&#34;它在一个数组中,然后尝试这个:
var data = [];
$( "ul.foundData li.id" ).each(function(idx, itm) {
data.push(index + ": " + $(itm).text());
});
console.log(data);
答案 3 :(得分:1)
var yourvariablearray = [];
$( "ul.foundData li.id" ).each(function(index) {
yourvariablearray.push((index + ": " + $(this).text()));
});
console.log(yourvariablearray);
答案 4 :(得分:0)
这是一个JavaScript解决方案
var allRelevantData = Array.slice.call(null,document.querySelectorAll("ul.foundData li.id")).map(function(ele,index){
return index +" : " + ele.innerText;
});
console.log(allRelevantData[0])// 0 : Product 0
console.log(allRelevantData[1])// 1 : Product 1
console.log(allRelevantData[2])// 2 : Product 2
console.log(allRelevantData[3])// 3 : Product 3
或者如果你想要可用的物体,那么你可以这样做:
var allRelevantData = Array.slice.call(null,document.querySelectorAll("ul.foundData li.id")).map(function(ele,index){
return {index : ele.innerText};
});
console.log(allRelevantData[0])// {0 : "Product 0"}
console.log(allRelevantData[1])// {1 : "Product 1"}
console.log(allRelevantData[2])// {2 : "Product 2"}
console.log(allRelevantData[3])// {3 : "Product 3"}