Javascript ';选定的';选项的属性不为';t在if-else语句中重置

Javascript ';选定的';选项的属性不为';t在if-else语句中重置,javascript,if-statement,html-select,Javascript,If Statement,Html Select,我试图使用if-else语句将“selected”添加到选择菜单中的选项中。我唯一的问题是,我不确定为什么一旦我返回到值“top”选项[1]仍然是“selected”。就像第一个if不执行条件一样,尽管我看到如果我执行控制台日志,它会变为第一个if <select id='selectdesign'> <option value="0"></option> <option value="top">top</option>

我试图使用if-else语句将“selected”添加到选择菜单中的选项中。我唯一的问题是,我不确定为什么一旦我返回到值“top”选项[1]仍然是“selected”。就像第一个if不执行条件一样,尽管我看到如果我执行控制台日志,它会变为第一个if

<select id='selectdesign'>
    <option value="0"></option>
    <option value="top">top</option>
    <option value="jeans">jeans</option>
</select>


<select id='selectmenu'>
    <option value="0"></option>
    <option value="1">top-blue</option>
    <option value="2">top-pink</option>
    <option value="3">bottoms-red</option>
    <option value="4">bottoms-violet</option>
</select>
function selectOption(element) {
        if (element.value == 'top') {
             console.log('if');
             option[2].setAttribute('selected', true);
        } else if (element.value == 'jeans') {
             console.log('else if');
             option[1].setAttribute('selected', true);  
        }
    }

顶部
牛仔裤
蓝色上衣
粉红色
底部是红色的
底部紫罗兰色
功能选择选项(元素){
如果(element.value=='top'){
console.log('if');
选项[2]。setAttribute('selected',true);
}else if(element.value='jeans'){
console.log('else if');
选项[1]。setAttribute('selected',true);
}
}

我正在调用selectDesign on change上的selectOption函数

您需要访问select元素的正确值,如

element.options[element.selectedIndex].value
和使用

document.getElementById('selectmenu').selectedIndex = 1;
用于设置选项的索引

功能选择选项(元素){
if(element.options[element.selectedIndex].value==“top”){
document.getElementById('selectmenu')。selectedIndex=1;
}else if(element.options[element.selectedIndex].value=='jeans'){
document.getElementById('selectmenu')。selectedIndex=3;
}
}

顶部
牛仔裤
蓝色上衣
粉红色
底部是红色的
底部紫罗兰色

也显示html代码此处定义了
选项
变量?请输入问题以显示所有相关代码。在任何情况下,您都可以通过直接设置select元素的
.value
属性来设置其当前值,而无需乱设置单个选项元素的
'selected'
属性。非常感谢!这就是我想要的。