jQuery 1.7以后 jQuery2 新元素绑定事件on替代live

时间:2023-03-09 02:48:43
jQuery 1.7以后 jQuery2 新元素绑定事件on替代live

最近做了一个类别动态加载的功能,jQuery版本用的是2.02。

jQuery 1.7以后 jQuery2 新元素绑定事件on替代live

绑定事件jQuery1.7之前用的是live或者是bind。新版的jQuery新增了on方法

由于子类别是动态加载的,默认是不会有事件加载的,要给他绑定一个change事件才能获取他的子类别。

然后定义一个handler,给on方法里面传值,上代码

//定义一个类别改变的事件hander
function classChangeHander() {
var thisinput = $(this);
thisinput.parent().nextAll().remove();
if (thisinput.val().trim() == "") {
return;
}
$.get("{:U('Admin/Item/getChildClass')}", {'class_id': thisinput.val()}, function (data) {
if (data.length) {
var optionStr = '<option value="">&nbsp;</option>';
data.forEach(function (item) {
optionStr += '<option value="' + item.class_id + '">' + item.class_name + '</option>';
});
var thisDepth = thisinput.data('depth') + 1;
thisinput.parent().after("<div class='col-sm-2'><select class='form-control' id='class_" + thisDepth + "' name='class_id' data-depth='" + thisDepth + "'>" + optionStr + "</select></div>");
var newId = 'class_' + thisDepth;
$("select[id^=" + newId + "]").on("change", classChangeHander);//绑定子类别的事件
}
}, 'json');
}
//class
$("select[id^='class_']").on("change", classChangeHander);//默认加载的时候绑定父类别下拉框的事件