• jquery操作select(取值,设置选中)


    每一次操作select的时候,总是要出来翻一下资料,不如自己总结一下,以后就翻这里了。

    比如<select class="selector"></select>

    1、设置value为pxx的项选中

         $(".selector").val("pxx");

    2、设置text为pxx的项选中

        $(".selector").find("option[text='pxx']").attr("selected",true);

        这里有一个中括号的用法,中括号里的等号的前面是属性名称,不用加引号。很多时候,中括号的运用可以使得逻辑变得很简单。

    3、获取当前选中项的value

        $(".selector").val();

    4、获取当前选中项的text

        $(".selector").find("option:selected").text();

        这里用到了冒号,掌握它的用法并举一反三也会让代码变得简洁。

     

    补充:很多时候用到select的级联,即第二个select的值随着第一个select选中的值变化。这在jQuery中是非常简单的。

    如:$(".selector1").change(function(){

         // 先清空第二个

          $(".selector2").empty();

         // 实际的应用中,这里的option一般都是用循环生成多个了

          var option = $("<option>").val(1).text("pxx");

          $(".selector2").append(option);

    });


    5、获取下拉列表中所有的option

    var sle = document.getElementById("selCmp").option;

    for (var i=0;i<sel.length;i++) {
    alert(se[i].text + ";" + se[i].value);

    }


    6、清空 Select:
     1>. $("#cusChildTypeId").empty();
     2>. $("#cusChildTypeId").get(0).options.length = 0; 


    7、删除select中值为value的项 
            var count = $("#cusChildTypeId").size();           
            for(var i=0;i<count;i++)   
            {   
                if($("#cusChildTypeId").get(0).options[i].value == value)   
                {   
                    $("#cusChildTypeId").get(0).remove(i);   
                    break;   
                }
            }


    8、向select中添加一项,显示内容为text,值为value   
     $("#cusChildTypeId").get(0).options.add(new Option(text,value));


    9、获取select选中的索引:
          $("#ddlRegType ").get(0).selectedIndex;


    10、得到select项的个数   
     $("#cusChildTypeId").get(0).options.length


    11、设置select 选中的索引:
         $("#cusChildTypeId").get(0).selectedIndex=index;//index为索引值


    12、设置select 选中的value:
        $("#cusChildTypeId").attr("value","Normal");
        $("#cusChildTypeId").val("Normal");
        $("#cusChildTypeId").get(0).value = "Normal";


    13、设置select 选中的text:
     1>.var count=$("#cusChildTypeId").get(0).options.length;
         for(var i=0;i<count;i++)  
             {           
      if($("#cusChildTypeId").get(0).options.text == text)  
             {  
                 $("#cusChildTypeId").get(0).options.selected = true;
                 break;  
             }  
            }
     2>.$("#cusChildTypeId").val(text);
        $("#cusChildTypeId").change();

  • 相关阅读:
    自动化测试框架相关资料下载
    C++白盒测试最佳实践课程,3个免费名额火热申请中,31号前截止申请...
    亿能测试培训中心 下周进入完整自动化测试项目实训阶段
    亿能测试大讲堂
    自动化测试调查问卷送《QTP自动化测试最佳实践》
    8月白盒测试课程
    广州亿能自动化测试沙龙
    8月自动化测试课程
    广州亿能自动化测试沙龙
    史上最强的自动化测试课程7月开设
  • 原文地址:https://www.cnblogs.com/heganlin/p/6016651.html
Copyright © 2020-2023  润新知