jQuery动态增加/删除select下来框的option中的selected属性

jQuery动态增加/删除select下来框的option中的selected属性

  • 1、说明:选中下拉框的时候,先清除所有选中的option选项
  • 2、效果截图:

1、说明:选中下拉框的时候,先清除所有选中的option选项

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src='jquery的包路径'></script>
</head>
<body>
  <select name="select" id="selID">
    <option value="0">下拉菜单一</option>
    <option value="1">下拉菜单二</option>
    <option value="2" selected="selected">下拉菜单三</option>
    <option value="3">下拉菜单四</option>
    <option value="4">下拉菜单五</option>
  </select>

  <script type="text/javascript">
    $(function () {
    //下拉框改变的时候触发
      $("#selID").change(function () {
      //遍历移除下拉框中所有option的属性为selected的选项
        $("#selID").each(function () {
          $(this).find("option").each(function () {
            if ($(this).attr("selected")) {
              //移除selected属性
              $(this).removeAttr("selected");
            }
          });
        });
        //添加selected属性
        $("#selID").find("option:selected").attr("selected", true);
      })
      alert($("#selID").find("option:selected").text())
    })
  </script>
</body>
</html>

2、效果截图:

jQuery动态增加/删除select下来框的option中的selected属性_第1张图片

你可能感兴趣的:(js,html,jquery)