您的位置:首页 > Web前端 > JQuery

jQuery为动态生成的select元素添加事件的方法

2016-08-29 00:00 891 查看
项目中需要在点击按钮时动态生成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("你点击了下拉框");
})


以上这篇jQuery为动态生成的select元素添加事件的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:

jquery html动态生成select标签出问题的解决方法
jQuery给动态添加的元素绑定事件的方法
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  jquery 动态 生成 select