[英]Arrays in javascript with jquery
I want to create an array with would hold all option element values and html text. 我想创建一个包含所有选项元素值和html文本的数组。 And in a result I would like something like this:
结果,我想要这样的事情:
console.log( myArray );
output: 输出:
[ "htmlText" : '0', "htmlText2" : '1', ... ]
if this is possible, how can I access them and get their keys? 如果可能的话,我该如何访问它们并获取其密钥?
or at least 2dim array 或至少2dim阵列
How Can I do that? 我怎样才能做到这一点?
this is what I have now: 这就是我现在所拥有的:
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;
}
The function can be simplified: 该功能可以简化:
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"}
Use {}
instead of []
to make an associative array. 使用
{}
代替[]
来创建一个关联数组。
var values = {
htmlText: 0,
htmlText2: 1,
};
console.log(values['htmlText']);
To append things to an associative array (also referred to as an object): 要将事物附加到关联数组(也称为对象):
values['stuff'] = 'foo';
values['thing'] = 'bar';
To loop over this: 要对此进行循环:
for (var key in values) {
/* check to make sure it's actually a valid key */
if (values.hasOwnProperty(key)) {
console.log(key + " => " + values[key]);
}
}
An object would suit your needs best in this case. 在这种情况下,一个对象将最适合您的需求。 You can use
map()
to create one from the option
elements in any given select
. 您可以使用
map()
从任意给定select
的option
元素中创建一个。 Try this: 尝试这个:
var values = $('#mySelect option').map(function() {
var obj = {};
obj[$(this).text()] = $(this).val();
return obj;
});
Given this HTML: 鉴于此HTML:
<select id="mySelect">
<option value="1">Foo</option>
<option value="2">Bar</option>
</select>
The returned object would look like this: 返回的对象如下所示:
[
{ "Foo": "1" },
{ "Bar": "2" }
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.