我的下拉菜单有点问题,我想在值不为 0 时验证它们,所以我使用了以下代码:
$('select[name=seguimento]').change(function(){
$('option:selected',this).attr('selected', true);
});
问题是,当我更改选项时,它会变为选中状态,但当我再次更改它时,它会一直将所有选项标记为选中状态,而不是删除已选中的选项。
我到处搜索,但没有找到解决方案。
我该怎么做? 谢谢!
最佳答案
您必须从未选择的选项元素中删除选择的属性,这样
$('select[name=seguimento]').change(function () {
$('option[selected]:not(:selected)', this).removeAttr('selected');
$('option:selected', this).attr('selected', true);
});
如果所有选项 elemnets 都是兄弟(即 optgroup
则不使用)
$('select[name=seguimento]').change(function () {
$('option:selected', this).attr('selected', true).siblings('[selected]').removeAttr('selected');
});
关于javascript - 使用 jquery 将下拉值标记为选中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31237590/