JQuery 获取多个select标签option的text内容

     根据option的id属性,修改text值

 


1  $("#sel_div .select_class option[id='-选择省-']").text(data.province).attr("selected",true);
2  $("#sel_div .select_class option[id='-选择市-']").text( data.city).attr("selected",true);
3  $("#sel_div .select_class option[id='-选择区-']").text( data.area).attr("selected",true);
4  $("#sel_div .select_class option[id='-选择街-']").text( data.street).attr("selected",true);

获取多个select(使用class属性,切值相同)下的所有option的text值

 1 $("#sel_div .select_class option").each(function(){ //遍历所有option标签
 2 
 3       var text = $(this).text(); //获取option的text
 4       alert(text);//显示的是当前这个option的text值
 5    if(txt == "选择省")
 6           $("#sel_div .select_class option[id='-选择省-']").text(data.province).attr("selected",true);
 7      if(txt == "选择市")
 8           $("#sel_div .select_class option[id='-选择市-']").text( data.city).attr("selected",true);
 9      if(txt == "选择区")
10          $("#sel_div .select_class option[id='-选择区-']").text( data.area).attr("selected",true);
11     if(txt == "选择街")
12          $("#sel_div .select_class option[id='-选择街-']").text( data.street).attr("selected",true);
13 
14  });

  如果select中间没有级联关系,那么所有的option都已经加载,可以使用下面的方法显示查询出来的数据

$("#sel_div .select_class option[id="+data.province+"]").attr("selected",true);
$("#sel_div .select_class option[id="+data.city+"]").attr("selected",true);
$("#sel_div .select_class option[id="+data.area+"]").attr("selected",true);
$("#sel_div .select_class option[id="+data.street+"]").attr("selected",true);

 

另一种获取所有option的方法,相当于将所有text拼成字符串,把每个字符存进map中

var map = $("#sel_div .select_class option").map(function(){
alert($(
this).text());//显示单个option的text text1
return $(this).text(); }).get().join(",");

alert(map);//显示的是 text1,text2,text3
alert(map[0]);//显示 t
在上面的基础上进行改进,使用array数组存放查询出来的数据,在使用for循环可以对数据进行操作
 var array = new Array();
    $("#leaf .form-control option").map(function(){
        array.push($(this).text());
    })
    for(var i = 0; i < array.length; i ++ ){
        alert(array[i]);//显示每个option的text   text1,text2,text3
    }

 

 
原文地址:https://www.cnblogs.com/gczmn/p/7486796.html