[英]Arrays in javascript with jquery
我想創建一個包含所有選項元素值和html文本的數組。 結果,我想要這樣的事情:
console.log( myArray );
輸出:
[ "htmlText" : '0', "htmlText2" : '1', ... ]
如果可能的話,我該如何訪問它們並獲取其密鑰?
或至少2dim陣列
我怎樣才能做到這一點?
這就是我現在所擁有的:
function optionValues( selectEl )
{
var values = [];
if ( selectEl.length )
{
$(selectEl).find('option').each( function(){
values.push( $(this).val() );
});
return values;
}
else
return false;
}
function optionHtmls( selectEl )
{
var html = [];
if ( selectEl.length )
{
$(selectEl).find('option').each( function(){
html.push( $(this).html() );
});
return html;
}
else
return false;
}
該功能可以簡化:
function optionValues(selectEl) {
var options = {};
$(selectEl).find('option').each(function() {
options[this.label] = this.value;
});
return options;
}
console.log(optionValues('select')) // {Text 1: "1", Text 2: "2", Text 3: "3"}
使用{}
代替[]
來創建一個關聯數組。
var values = {
htmlText: 0,
htmlText2: 1,
};
console.log(values['htmlText']);
要將事物附加到關聯數組(也稱為對象):
values['stuff'] = 'foo';
values['thing'] = 'bar';
要對此進行循環:
for (var key in values) {
/* check to make sure it's actually a valid key */
if (values.hasOwnProperty(key)) {
console.log(key + " => " + values[key]);
}
}
在這種情況下,一個對象將最適合您的需求。 您可以使用map()
從任意給定select
的option
元素中創建一個。 嘗試這個:
var values = $('#mySelect option').map(function() {
var obj = {};
obj[$(this).text()] = $(this).val();
return obj;
});
鑒於此HTML:
<select id="mySelect">
<option value="1">Foo</option>
<option value="2">Bar</option>
</select>
返回的對象如下所示:
[
{ "Foo": "1" },
{ "Bar": "2" }
]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.