JavaScript與DropDownList 區別分析
2024-05-06 14:12:01
供稿:網友
比如<asp:LinkButton>控件就被渲染成了<a>錨點控件,這里要講的DropDownList控件也一樣,被渲染成了普通的select控件,在如下的asp.net頁面中定義了一個web服務器控件DropDownList和一個普通的select控件(主要為了對比)。
代碼
代碼如下:
<asp:DropDownList ID = "ddlCities" runat = "server">
<asp:ListItem Value = "0">長沙</asp:ListItem>
<asp:ListItem Value = "1">北京</asp:ListItem>
<asp:ListItem Value = "2">天津</asp:ListItem>
<asp:ListItem Value = "3">漠河</asp:ListItem>
</asp:DropDownList>
<select id = "ddlNames" runat ="server">
<option value = "0">James</option>
<option value = "1">Green</option>
<option value = "2">Lily</option>
<option value = "3">Lucy</option>
</select>
在瀏覽器中查看該頁面,并點擊查看源文件,不難看出,asp.net頁面被渲染成了如下格式:
代碼
代碼如下:
<select name="ddlCities" id="ddlCitys">
<option value="0">長沙</option>
<option value="1">北京</option>
<option value="2">天津</option>
<option value="3">漠河</option>
</select>
<select name="ddlNames" id="ddlNames">
<option value="0">James</option>
<option value="1">Green</option>
<option value="2">Lily</option>
<option value="3">Lucy</option>
</select>
好了,接下來介紹一下要用javascript操縱DropDownList控件,首先得了解select(或者DropDownList)的兩個最基本的屬性,一個是value屬性,一個是text屬性,還有一個selectedIndex屬性,用來標識當前選中的項(數字),具體可參見上面的示例代碼。
下面正式言歸正傳,主要介紹如下幾點:
(1) 清空DropDownList控件中的值。
document.getElementById('ddlCities').options.length = 0;
(2) 判斷DropDownList中是否有value為'Param1'的ListItem。
代碼如下:
function isListItemExist(objDdl , objItemValue)
{
var isExist = false;
for(var i in objSelect.options)
{
if(i.value == objItemValue)
{
isExist = true;
break;
}
}
return isExist;
}
JavaScript與DropDownList
服務器控件DropDownList和Javascript的之間的傳遞
代碼如下:
<script language="javascript">
function hehe()
{
document.all('txtSdept').value =document.all('ddlSdept').options[document.all('ddlSdept').selectedIndex].text;
}
</script>
<asp:DropDownList id="ddlSdept" style="Z-INDEX: 101; LEFT: 240px; POSITION: absolute; TOP: 112px" onchange="hehe()" runat="server">
<asp:ListItem Value="1">計算機系</asp:ListItem>