Javascript 如何在更改select标记时切换选定的true或false?

Javascript 如何在更改select标记时切换选定的true或false?,javascript,html,dom,html-select,Javascript,Html,Dom,Html Select,我有一个带有n个选项的select标记。我需要将所选选项设置为true,并将其他选项设置为false。当onchange函数触发时,true应该切换 我的代码如下: let techDropClone = document.getElementsByTagName("select")[0]; let opt = techDropClone.options; opt[techDropClone.selectedIndex].setAttribute("selected",true); 我知道上面

我有一个带有n个选项的select标记。我需要将所选选项设置为true,并将其他选项设置为false。当onchange函数触发时,true应该切换

我的代码如下:

let techDropClone = document.getElementsByTagName("select")[0];
let opt = techDropClone.options;
opt[techDropClone.selectedIndex].setAttribute("selected",true);

我知道上面的代码不会切换为true,但我不知道如何实现这一点。

$('button').on('click',function(){var chbx=$('input[type=checkbox]);$.each(chbx,function(index,value){console.log(value.id+':'+value.checked);})

$('button')。在('click',function(){var chbx=$('input[type=checkbox]');$。每个(chbx,function(index,value){console.log(value.id+':'+value.checked);})

一个普通的js解决方案可以是:

let techDropClone = document.getElementsByTagName("select")[0];
let opt = techDropClone.options;

for(var i=0; i<opt.length; i++){
    if(i == techDropClone.selectedIndex){
        opt[i].setAttribute("selected",true);
    }else{
        opt[i].setAttribute("selected",false);
    }
}
让techDropClone=document.getElementsByTagName(“选择”)[0];
让opt=techDropClone.options;

对于(var i=0;i一个普通的js解决方案可以是:

let techDropClone = document.getElementsByTagName("select")[0];
let opt = techDropClone.options;

for(var i=0; i<opt.length; i++){
    if(i == techDropClone.selectedIndex){
        opt[i].setAttribute("selected",true);
    }else{
        opt[i].setAttribute("selected",false);
    }
}
让techDropClone=document.getElementsByTagName(“选择”)[0];
让opt=techDropClone.options;

对于(var i=0;i您可以尝试以下方法:

函数myfunc(el){
document.querySelectorAll('select option').forEach(函数(op){
op.removeAttribute(“选定”);
});
设techDropClone=el;
让opt=techDropClone.options;
opt[techDropClone.selectedIndex].setAttribute(“已选”,true);
}
myfunc(document.querySelector('select');

沃尔沃汽车
萨博
梅赛德斯
奥迪

您可以尝试以下方法:

函数myfunc(el){
document.querySelectorAll('select option').forEach(函数(op){
op.removeAttribute(“选定”);
});
设techDropClone=el;
让opt=techDropClone.options;
opt[techDropClone.selectedIndex].setAttribute(“已选”,true);
}
myfunc(document.querySelector('select');

沃尔沃汽车
萨博
梅赛德斯
奥迪

可能重复的可能重复的可能重复的似乎他没有使用jQuery似乎他没有使用jQuery