最代码官方的gravatar头像
最代码官方 2015-11-29 23:11:30

jQueryV1.7.2替换为V1.10.2后live方法替换为on方法对动态添加元素的事件绑定的解决方案

jquery对后台返回的html dom的元素绑定事件可以通过

$("#div_id_name .div_class_name").click(function() {
//process
}

方法来绑定,但是对于js动态新加的元素,比如通过ajax从后台获取到最新评论列表的数据后append到评论div的元素是无法绑定js事件的,jquery1.7的可以live方法动态绑定所有元素的事件:

$("#div_id_name .div_class_name").live(function() {
//process
}

但是今天替换为jquery v1.10.2后明确提示没有找到live方法,通过查找资料发现新版本已经去掉了live,该为on方法,具体用法如下:

$(document).on("click",".reply_no_editor",function() {
	var content_id = $(this).attr("content_id");
	var content = $("#" + content_id);
	var textarea_id = $(this).attr("textarea_id");
	var textarea = $("#" + textarea_id);
	var name = $(this).attr("name");
	textarea.val("回复@" + name + " 说:");
	textarea.scrollTo(100).focus();
});

jQueryV1.7.2替换为V1.10.2后live方法替换为on方法对动态添加元素的事件绑定的解决方案

具体可以参考http://static.zuidaima.com/resource/js/javaniu.js?v=20151029的实现

$(document).on("click",".reply_no_editor",function() {

希望对牛牛们有帮助。


打赏

顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友