事件上的jQuery不适用于动态元素 [英] Jquery on event not working for Dynamic elements

查看:118
本文介绍了事件上的jQuery不适用于动态元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$(".spanCont:first .collection_shop").on("click",function(){
            var current_item = $(this);
            $.ajax({
                url: "ajax/abc.php",
                type: "POST",
                dataType: 'html',
                data: {collection_id: current_item.attr("value")},
                beforeSend: function(xhr) {
                    current_item.replaceWith("<div id='temp_div'></div>");
                }
            }).done(function(data){
                $(".spanCont:first .span-2, .spanCont:first input").remove();
                $("#temp_div").replaceWith(data);
            });
        });

此代码应适用于所有具有.collection_shop类的元素的静态和动态单击,但仅适用于静态元素.

This code should work for all static and dynamic click of elements with class .collection_shop but its only working for static elements.

推荐答案

您应使用 事件委托

$(document).on("click",".spanCont:first .collection_shop",function(){
   //some operation
});

它可以帮助您为动态元素附加处理程序

It helps you to attach handlers for dynamic elements

这篇关于事件上的jQuery不适用于动态元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆