ASP.NET jQuery 食譜8 (動(dòng)態(tài)添加內(nèi)容到DropDown
系統(tǒng)
2410 0
在web應(yīng)用里,我們經(jīng)常需要通過(guò)其他控件的事件觸發(fā)動(dòng)態(tài)構(gòu)造DropDownList數(shù)據(jù)內(nèi)容。
在這節(jié)中,我們將會(huì)看到如何實(shí)現(xiàn)通過(guò)選擇第一個(gè)下來(lái)框的內(nèi)容來(lái)動(dòng)態(tài)構(gòu)造第二個(gè)下拉框的內(nèi)容。
首先準(zhǔn)備好頁(yè)面代碼:
View Code
<
form
id
="form1"
runat
="server"
>
<
div
align
="left"
>
<
fieldset
style
="width: 350px; height: 150px"
>
<
p
>
選擇顏色
</
p
>
<
table
cellpadding
="0"
cellspacing
="0"
border
="0"
>
<
tr
>
<
td
>
</
td
>
<
td
>
<
asp:DropDownList
ID
="ddlFirst"
runat
="server"
>
<
asp:ListItem
Value
=""
Text
="--- 請(qǐng)選擇 ---"
></
asp:ListItem
>
<
asp:ListItem
Value
="1"
Text
="紅色"
></
asp:ListItem
>
<
asp:ListItem
Value
="2"
Text
="黃色"
></
asp:ListItem
>
<
asp:ListItem
Value
="3"
Text
="藍(lán)色"
></
asp:ListItem
>
</
asp:DropDownList
>
</
td
>
</
tr
>
<
tr
>
<
td
colspan
="2"
>
</
td
>
</
tr
>
<
tr
>
<
td
>
</
td
>
<
td
>
<
asp:DropDownList
ID
="ddlSecond"
runat
="server"
>
<
asp:ListItem
Value
=""
Text
="--- 請(qǐng)選擇 ---"
></
asp:ListItem
>
</
asp:DropDownList
>
</
td
>
</
tr
>
</
table
>
</
fieldset
>
</
div
>
</
form
>
主要通過(guò)jQuery的append方法動(dòng)態(tài)添加內(nèi)容,腳本代碼如下:
<
head
runat
="server"
>
<
title
>
Recipe8
</
title
>
<
script
src
="Scripts/jquery-1.4.1-vsdoc.js"
type
="text/javascript"
></
script
>
<
script
type
="text/javascript"
>
$(document).ready(
function
() {
$(
"
#ddlFirst
"
).bind(
"
change
"
,
function
() {
//
添加change事件
$(
"
#ddlSecond option
"
).remove();
//
先刪除所有項(xiàng),以便重新加載
$(
"
#ddlSecond
"
).append(
"
<option value=''>--- 請(qǐng)選擇 ---</option>
"
);
if
($(
this
).val()
==
1
) {
$(
"
#ddlSecond
"
).append(
"
<option value='11'>紅色1</option>
"
);
$(
"
#ddlSecond
"
).append(
"
<option value='12'>紅色2</option>
"
);
$(
"
#ddlSecond
"
).append(
"
<option value='13'>紅色3</option>
"
);
}
else
if
($(
this
).val()
==
2
) {
$(
"
#ddlSecond
"
).append(
"
<option value='21'>黃色1</option>
"
);
$(
"
#ddlSecond
"
).append(
"
<option value='22'>黃色2</option>
"
);
$(
"
#ddlSecond
"
).append(
"
<option value='23'>黃色3</option>
"
);
}
else
if
($(
this
).val()
==
3
) {
$(
"
#ddlSecond
"
).append(
"
<option value='31'>藍(lán)色1</option>
"
);
$(
"
#ddlSecond
"
).append(
"
<option value='32'>藍(lán)色2</option>
"
);
$(
"
#ddlSecond
"
).append(
"
<option value='33'>藍(lán)色3</option>
"
);
}
});
});
</
script
>
</
head
>
最終顯示效果如下:
動(dòng)態(tài)添加內(nèi)容還可以通過(guò)以下方式添加:
$("#ddlSecond").append($("<option></option>").val("31").html("
藍(lán)色1
"));
ASP.NET jQuery 食譜8 (動(dòng)態(tài)添加內(nèi)容到DropDownList)
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫(xiě)作最大的動(dòng)力,如果您喜歡我的文章,感覺(jué)我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元