項目中需要在點擊按鈕時動態生成select元素,為防止每次點擊按鈕時從服務器端獲取數據(因為數據都是相同的),可以這樣寫代碼
1、首先定義全局js變量
var strVoucherGroupSelect ="";
2、在js中寫好獲取服務端數據的代碼
function
genVoucherGroupSelect(rowID){
return
$(strVoucherGroupSelect).attr(
"id"
,
"sl_"
+ rowID).parent().html();
//返回增加ID后的下拉框完整html
}
function
getVoucherGroupData(){
$.ajax({
type:
"Post"
,
url:
"/BillWeb/OrgVoucher/GetVoucherGroup"
,
dataType:
"json"
,
data:
""
,
cache:
true
,
success:
function
(res) {
var
str = $(
"<select></select>"
);
var
option =
""
;
for
(
var
j =0;j < res.length; j++)
{
option +=
"<option value=\""
+ res[j].Value +
"\">"
+ res[j].Text +
"</option>"
;
}
strVoucherGroupSelect = $(str).html(option).parent().html();
}
});
}
3 在頁面中編寫初始化代碼
$().ready(
function
(){
getVoucherGroupData();
});
4 需要動態增加select的時候,可以這樣寫
$(
"#divID"
).append(genVoucherGroupSelect(rowID) );
5 給select增加點擊事件,在第四步后增加
$(
"#sl_0"
+ rowID).bind(
"change"
,
function
(){
alert(
"你點擊了下拉框"
);
})