select設置選中項/select的級聯

1、selected="selected"

HTML經過<select>的屬性來設置選中項,jquery

此方法也能夠在動態語言在後臺根據須要控制輸出結果。app

<select ID='sel' class="form-control width150">  
 <option value="1">開啓</option>  
<option selected="selected" value="0">關閉</option>   <!-- selected="selected" 默認選擇 -->
</select>

 

2、js來設置選中項:修改selected屬性值

<script >
var  ss = document.getElementById('sel');
ss[0].selected = true;//選中
</script>

 

3、jquery設置選中項- 設置指定value爲項中

  1.設置value爲vxx的項選中flex

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

     如:   $("#sel").eq(0).val("0");    

 

 

4、jquery設置選中項- 設置指定text爲項中  

1.設置text爲txx的項選中this

    $(".selector").find("option:contains('pxx')").attr("selected",true);spa

1   $(".select").eq(0).find("option:contains('關閉')").attr("selected", true);
2             var opt = $(".select").eq(0).find("option:contains('關閉')");
3             console.log(opt);                         //obj {...}
4             console.log(    opt.attr("selected"));  // selected

第四行 顯示結果——code

 selectedorm

 

  2.注意:blog

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

1   var opt = $(".select").eq(0).find("option[text='關閉']");
2    console.log(opt);                                      //obj{...}
3    console.log(    opt.attr("selected"));            // undefined

第三行顯示結果——get

undefined

 

三、注意:獲取當前選中項的value

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

四、注意:獲取當前選中項的text

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

 

5、select的級聯

即第二個select(obj2)的值隨着第一個select(obj1)選中的值變化,第三個第四個等其餘select(other)也跟着變化

function GetChildrenData(dataobj, obj1, obj2,  other) {
    obj1.change(function () {

        var obj2Text = obj2.find("option").eq(0).text(); //請選擇...
        obj2.empty();
        obj2.append('<option value="">' + obj2Text + '</option>');
     

        if(other !=null )
        for (var i = 0; i < other.length; i++) {
            var otherText = other[i].find("option").eq(0).text(); //請選擇...
            other[i].empty();
            other[i].append('<option value="">' + otherText + '</option>');
        }
        if ($(this).val() != "") {
            dataobj.GetChildredData($(this).val(), function (re) {
                try {
                    var ds = JSON.parse(re.value).Table;
                    for (var i = 0; i < ds.length; i++) {
                        obj2.append('<option value="' + ds[i].ID + '">' + ds[i].Name + '</option>');
                    }
                } catch (e) { }
            })
        }
    })
}
相關文章
相關標籤/搜索