2017-09-26 66 views
1

我试图从数组中填充选择框。我需要价值与文本不同。如何在具有多个值的数组上迭代

到目前为止,这个代码工作,因为我得到了正确的价值观:

var myArray = []; 
$('#ctl00_ContentPlaceHolderBody_labelTider > div').each(function() { 
    myArray.push({ 
     content: $(this).find('th').text(), 
     id: $(this).attr('id') 
    }); 
}); 
console.log(myArray); 

不过,我一直无法弄清楚,或通过谷歌找到,如何遍历低谷这些并获得价值。

for(arr = 0; arr < myArray.length; arr++) { 

    jQuery('<option/>', { 
     value: myArray[arr], 
     text: myArray[arr] 
    }).appendTo('.selectLocation'); 
} 

这导致[object Object]

任何人都可以指导我在正确的方向,将不胜感激。

回答

0

的问题是因为你设置整个对象的属性值,而不是从该对象的相关属性。试试这个:

for(arr = 0; arr < myArray.length; arr++){ 
    jQuery('<option/>', { 
    value: myArray[arr].content, 
    text: myArray[arr].id 
    }).appendTo('.selectLocation'); 
} 

请注意,您可以通过使用map()使代码更succint创建一个包含HTML字符串数组,然后join()它一起为您附加:

var html = $('#ctl00_ContentPlaceHolderBody_labelTider > div').map(function() { 
    return `<option value="${this.id}">${$(this).find('th').text()}</option>`; 
}).get(); 
$('.selectLocation').append(html.join('')); 
0

使用 ​​对于值 和 value: myArray[arr].id因为您的myArray是对象数组。

for(arr = 0; arr < myArray.length; arr++){ 

     jQuery('<option/>', { 
     value: myArray[arr].content, 
     text: myArray[arr].id 
      }).appendTo('.selectLocation'); 
    }