Javascript 更改对象数组中的布尔值
我有单选按钮,我需要将所选单选按钮更改为true,将其他更改为falseJavascript 更改对象数组中的布尔值,javascript,Javascript,我有单选按钮,我需要将所选单选按钮更改为true,将其他更改为false changeHandler (index, event) { this.array[index].checked = true; } 我有以下数组结构: [ {checked: false, title: 'first'}, {checked: false, title: 'second'}, {checked: false, title: 'third'} ] 当我选择radio“first”时,我需要
changeHandler (index, event) {
this.array[index].checked = true;
}
我有以下数组结构:
[
{checked: false, title: 'first'},
{checked: false, title: 'second'},
{checked: false, title: 'third'}
]
当我选择radio“first”时,我需要将此obj值更改为true,将其他值更改为false,依此类推。您可以将所有选中的
成员设置为false,但具有选定索引的成员:
changeHandler (index, event) {
this.array.forEach((elem, idx) => elem.checked = idx == index);
}
您可以通过标题找到所有输入,并添加事件侦听器
以下是我的实现:
//文档加载后
常量myRadioButtons=[
{选中:false,标题:'first'},
{选中:false,标题:'second'},
{选中:false,标题:'third'}
];
myRadioButtons.forEach(单选=>{
函数updateRadioValue(id,value){
document.querySelector(`${id}`)。checked=value;
myRadioButtons.find(item=>item.title==id)。checked=value;
}
功能检查RadioAndResetOthers(){
我的单选按钮
.filter(item=>item.title!==radio.title)
.forEach(item=>updateRadioValue(item.title,false));
radio.checked=true;
控制台日志(myRadioButtons);
}
文件
.querySelector(`${radio.title}`)
.addEventListener(“更改”、检查Radio和SetOthers);
})
首先
第二
第三个
参见
const数组=[
{选中:false,标题:'first'},
{选中:false,标题:'second'},
{选中:false,标题:'third'}
];
函数changeHandler(索引){
array.forEach((item,i)=>item.checked=index==i);
}
changeHandler(0)
console.log(数组);
变更处理程序(1)
console.log(数组);
变更处理程序(2)
console.log(数组)
你能包含你的HTML和javascript吗?请向我们展示你的完整代码和HTML。我们无法完全理解您到底在寻找什么。