gpt4 book ai didi

javascript - 如何将选择选项插入对象数组中

转载 作者:太空宇宙 更新时间:2023-11-04 03:28:39 24 4
gpt4 key购买 nike

如何将选择 选项插入对象数组中,以便它构成单个选择框

我试过了

  <select name="fruit">
<option selected="true" value="apple">apple</option>
<option value="banana">banana</option>
<option value="kela">kela</option>
</select>


var fruits = [];
$('#fruits').find('select').each(function(){
fruits.push({
selectName: $(this).attr('name'),
optionValue: $(this).attr('value')

});
});

console.log(fruits);

我的问题:如何推送所有选项值,以便我可以获得一个选择框?我的意思是数组对象必须属于单个选择

var fruits = [];
$('#fruits').find('select').each(function(){
fruits.push({
selectName: $(this).attr('name'),
optionValue: [] // i want all the options values to be contained either in array or any other way

});
});

console.log(fruits);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div id="fruits">
<select name="fruit"><option selected="true" value="apple">apple</option><option value="banana">banana</option><option value="kela">kela</option></select>
</div>

最佳答案

我知道两种方法,如何做到这一点

var fruits = [];
$('#fruits').find('select').children().each(function(){
fruits.push({
selectName: $(this).parent().attr('name'),
optionValue: $(this).attr('value') // all the options value

});
});
console.log(fruits);

/*var fruits = [];
$('#fruits').find('select').children().each(function(){
fruits.push({
selectName: $(this).parent().attr('name'),
optionValue: $(this).attr('value') // all the options value

});
});
console.log(fruits);*/

var select = {};
$('#fruits').find('select').each(function(){
var propName = $(this).attr('name');
select[propName] = [];
$(this).children().each(function(){
select[propName].push({
selectName: $(this).text(),
optionValue: $(this).attr('value') // all the options value
});
});
});

console.log(select);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div id="fruits">
<select name="fruit"><option selected="true" value="apple">apple</option><option value="banana">banana</option><option value="kela">kela</option></select>
<select name="vegetable"><option selected="true" value="potato">potato</option><option value="tomato">tomato</option><option value="cabbage">cabbage</option></select>
</div>

关于javascript - 如何将选择选项插入对象数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41184963/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com