js操作select

1.select默认是inline元素,你可以
 
select
{
    display:block;
}
2.默认select会选择第一项option,如果初始状态不选可以:
jq写法:
$("select").each(function(){this.selectedIndex=-1});
或者干脆加个冗余option:
 
<select>
    <option>请选择网站...</option>
    <option value="http://www.qq.com">腾讯网</option>
    <option value="http://www.163.com">网易</option>
    <option value="http://www.google.com">谷歌</option>
</select>
注:
 
The selectedIndex property returns -1 if a select object does not contain any selected items. Setting the selectedIndex property clears any existing selected items.
 
The selectedIndex property is most useful when used with select objects that support selecting only one item at a time—that is, those in which the MULTIPLE attribute is not specified. 
3.获取选择项的值:
 
<select id="ddlCities" onchange="alert(this.options[this.selectedIndex].value);">
    <option value="0">北京</option>
    <option value="1">济南</option>
    <option value="2">威海</option>
</select>
获取文本:
 
this.options[this.selectedIndex].text
更简洁的直接selectObj.value
 
4.多选
 
<select id="ddlCities" multiple="multiple" size="2">
    <option value="0">北京</option>
    <option value="1">济南</option>
    <option value="2">威海</option>
</select>
 使用jq获取选择,仅测试所以写在标签上:
 
<select id="ddlCities" multiple="multiple" size="2" onchange="alert($(this).find('option:selected').text());">
    <option value="0">北京</option>
    <option value="1">济南</option>
    <option value="2">威海</option>
</select>
如果纯js写,需要循环了:
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style type="text/css">
select
{
    display:block;
}
</style>
<script type="text/javascript">
function ddlCities_onchange(theSel)
{
    var arr=[];
    for(var i=0;i<theSel.options.length;i++)
    {
        if(theSel.options[i].selected)
            arr.push(theSel.options[i].innerText);  
    }
    alert(arr.join());
}
</script>
</head>
 
<body>
<select>
    <option>请选择网站...</option>
    <option value="http://www.qq.com">腾讯网</option>
    <option value="http://www.163.com">网易</option>
    <option value="http://www.google.com">谷歌</option>
</select>
 
<select id="ddlCities" multiple="multiple" size="2" onchange="ddlCities_onchange(this);">
    <option value="0">北京</option>
    <option value="1">济南</option>
    <option value="2">威海</option>
</select>
</body>
</html>
5.添加移除option:
jq添加:
$("<option value='3'>南京</option>").appendTo($("#ddlCities"));
js写法:
 
var anOption = document.createElement("option");
anOption.text="南京";
anOption.value="4";
document.getElementById("ddlCities").options.add(anOption);
或者 document.getElementById("ddlCities").add(anOption);

你可能感兴趣的:(js操作select)