在jsavaScript中設定select的某個選項被選中

舟之橋發表於2013-03-13

轉載地址:http://www.2cto.com/kf/201107/97261.html


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);

相關文章