【jq】JQuery对select的操作

下拉框

<select id="selectID" name="selectName">

 <option vlaue="1">1</option>

 <option vlaue="2">2</option>

 <option vlaue="3">3</option>

</select>

(一)JQuery对select的操作

     // 获取select本身属性name的值

      console.log($("#selectID").prop("name"));

(二)JQuery对select option的操作

//选择更改事件

$("#selectID").change(function(){   selectChangeFunCode;      });     

//获取属性值

        //获取下拉框选中项的text属性值
        var selectText = $("#selectID").find("option:selected").text();
        console.log(selectText);
        //获取下拉框选中项的value属性值    ①
        var selectValue = $("#selectID").val();
        console.log(selectValue);
        //获取下拉框选中项的index属性值
        var selectIndex = $("#selectID").get(0).selectedIndex;
        console.log(selectIndex);
        ////获取下拉框最大的index属性值
        var selectMaxIndex = $("#selectID option:last").attr("index");
        console.log(selectMaxIndex);

//获取文本值

      //获取下拉框选中项的  文本内容     ②

      var selectHtml = $("#selectID").find("option:selected").html();
      console.log(selectHtml );

 要更改 下拉框其中一个option,需要同时操作①②

       //设置下拉框index属性为5的选项 选中
        $("#selectID").get(0).selectedIndex = 5;  
  
        //设置下拉框value属性为4的选项 选中
        $("#selectID").val(4);

        //设置下拉框text属性为5的选项 选中
         $("#selectID option[text=5]").attr("selected", "selected");
         $("#yyt option:contains('5')").attr("selected", true);

        //在下拉框最后添加一个选项
        $("#selectID").append("<option value='7'>7</option>");
  
        //在下拉框最前添加一个选项
        $("#selectID").prepend("<option value='0'>0</option>")

        //移除下拉框最后一个选项
        $("#selectID option:last").remove();

        //移除下拉框 index属性为1的选项
        $("#selectID option[index=1]").remove();
   
        //移除下拉框 value属性为4的选项
        $("#selectID option[value=4]").remove();

        //移除下拉框 text属性为5的选项
        $("#selectID option[text=5]").remove();

 

posted @ 2017-08-22 21:30  蓿苜  阅读(559)  评论(0编辑  收藏  举报