当前位置:Gxlcms > JavaScript > jquery如何让select选中某个选项的实例详解

jquery如何让select选中某个选项的实例详解

时间:2021-07-01 10:21:17 帮助过:10人阅读

jquery如何让select选中某个选项的实例详解

<span id="xx">广州市</span>
<select id="select_id">    
<option>北京市</option>    
<option>广州市</option>    
<option>上海市</option>
</select>

让select 选中 广州市 ?
错误用法:

$("#select_id option[text='广州市']").attr("selected", true); 
<script>
//普通js写法
document.getElementById("select_id").options[1].setAttribute("selected", true);
//jquery应该这样写
$("#select_id option").eq(1).attr("selected",true);
</script>
<script>
   $("#select_id option[value='广州市']").attr("selected", true);
</script>
$("#select_id option[text='广州市']").attr("selected", "selected");


正确用法:

 $("#select_id")[0].selectedIndex = 1;

jquery如何设置select索引选中,直接用dom操作方式操作索引:

$('#selectId').get(0).selectedIndex=index;

用值方式操作索引:

$('#selectId').val('selectIndexValue');


扩展:
获取当前选中项的value

$("#select_id").val();

获取当前选中项的text

$("#select_id").find("option:selected").text();

以上就是jquery如何让select选中某个选项的实例详解的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行