我在下面编写了html脚本
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<select id="drop_down_id">
<option value="1">Volvo</option>
<option value="2">Saab</option>
<option value="3">Opel</option>
<option value="4">Audi</option>
</select>
</body>
</html>
对于这个html,我正在使用下面的代码动态选择选项
var theText = "Saab";
$("#drop_down_id option:contains(" + theText + ")").attr('selected', 'selected').change();//If we not using change() also it'll work
在第一次它工作正常,但当我第二次使用相同的选项,它不是选择选项
说明
让我们假设,我第一次选择了值Saab
,然后我选择了Volvo
和Audi
。如果再次尝试选择Saab
或Volvo
或Audi
,则不会选择该选项。任何人都知道如何在jQuery
或JavaScript
实现它
选择一个选项后,它会将selected
属性添加到该选项。您没有删除现有的选定选项因此,在尝试再次选择之前,应从现有选项中删除所选属性
https://jsfiddle.net/9v8way30/6/
$(document).ready(function(){
var theText = "Audi";
$("#drop_down_id option:contains(" + theText + ")").attr('selected', 'selected').change();
theText = "Saab";
$("#drop_down_id option:contains(" + theText + ")").attr('selected', 'selected').change();
$('#drop_down_id option').removeAttr('selected');
theText = "Audi";
$("#drop_down_id option:contains(" + theText + ")").attr('selected', 'selected').change();
})
The above code adds the 'selected' attribute for each option which you are changing dynamically. Initially you need to remove the existing selected attribute from options
$("#drop_down_id").on('change', function() {
var value = $(this).val();
$(this).find('option').removeAttr("selected");
$(this).find('option[value="' + value + '"]').attr("selected", "selected");
});