目前我有一个选择选项下拉字段。当用户从下拉列表中选择选项选项时,将返回索引值。根据索引值,我想将"Selected"
值从false
更改为true
。
var users = [
{
"name": "John",
"selected": false,
"columns": [
{
"index": 0,
...
}
]
},
{
"name": "Sam",
"selected": false,
"columns": [
{
"index": 1,
...
}
]
}
]
因此,如果具有索引值0
的用户选择了第一个选项,请说明。这应该将第一个对象文字"Selected"
值更新为true
:
var users = [
{
"name": "John",
"selected": true,
"columns": [
{
"index": 0,
...
}
]
},
{
"name": "Sam",
"selected": false,
"columns": [
{
"index": 1,
...
}
]
}
]
答案 0 :(得分:2)
您可以捕获下拉列表的selectedIndex并迭代users
检查此示例
var selectElem = document.getElementById('select');
selectElem.addEventListener('change', function() {
var index = selectElem.selectedIndex;
users = users.map( function(user){
user.selected = user.columns[0].index == index; //this will set the rest of the selected values to false and only selected index to true
return user;
})
})
<强>演示强>
var users = [
{
"name": "John",
"selected": true,
"columns": [{ "index": 0 }]
},
{
"name": "Sam",
"selected": false,
"columns": [{ "index": 1 }]
}
];
var selectElem = document.getElementById('select');
selectElem.addEventListener('change', function() {
var index = selectElem.selectedIndex;
users = users.map( function(user){
user.selected = user.columns[0].index == index;
return user;
});
console.log( "updated users ", users );
})
<select id="select">
<option>John</option>
<option>Sam</option>
</select>