jquery click事件未在动态创建的div上触发

时间:2012-03-16 20:32:48

标签: jquery events dynamic binding click

我在div上设置了一个click事件,该事件是在jqueryUI drop事件(draggable的一部分)中动态创建的,click事件将删除div。这很好。在document.ready内部,我根据本地存储的数据做同样的事情。我可以创建动态div,但click事件不绑定,或者绑定丢失。我尝试过使用“点击”,“直播”和“开启”。我还删除了它所在的循环并且只是附加到第一个项目,直接坐在$(document).ready中它都不起作用,但是当我在drop事件中设置单击时工作正常。

这有效:从droppable

绑定
$( "#planView" ).droppable({
            drop: function( event, ui ) {
                if(ui.draggable.find(".planButton").length == 1){
                    // make unique ID,add ID to last child,add click event last child,add plan to model with plan data and ID 
                    var id      = ui.draggable[0].id; // we use the id to grab the right cart html and cart data
                    var id      = id.substring(0, id.length-6);
                    var newPlan;
                    var newID;
                    var planData;

                    $( this ).append(planCartObjects[id]);
                    newPlan         = $( this ).find('>:last-child');
                    newID           = "cartObject"+cartIDcounter++;
                    newPlan.attr("id",newID);
                    planData        = $.extend(true,{},planDataObjects[id]); //makes a copy of the data object
                    planData.id     = newID;
                    shoppingCart.addPlan(planData);
                    shoppingCart.logCart();
                    newPlan.click(function(){
                        //remove element
                        $(this).remove();
                        shoppingCart.removePlan(newID);
                        console.log("newID "+newID);
                    });
                }
            }

这不起作用 - 在document.ready上调用一次

    $(document).ready(function() {
        //check local storage 
        //if yes create plan and or feature cart objects
        //populate model
        var cartIDcounter       = 0;
        var localStorageKey     = "vlocalstore234"; 
        var shoppingCart;

        shoppingCart            = shoppingCartMaker({});

        if(localStorage.getItem(localStorageKey)){
            //grab cartModel, clear out local storage, calladdplan ans addfeature in a loop to create htmls objs and data obj
            var cartModel = JSON.parse(localStorage.getItem(localStorageKey));
            localStorage.removeItem(localStorageKey);
            //update cart with saved features and plans
            var i;
            var l                   = cartModel.plans.length;
            var newPlan;
            var newID;
            var planData;
            var id;

            for(i=0;i<l;i++){
                console.log(cartModel.plans[i].name);   
                id                  = cartModel.plans[i].name
                $( "#planView" ).append(planCartObjects[id]);
                    newPlan         = $( this ).find('>:last-child');
                    newID           = "cartObject"+cartIDcounter++;
                    newPlan.attr("id",newID);
                    planData        = $.extend(true,{},planDataObjects[id]); //makes a copy of the data object
                    planData.id     = newID;
                    shoppingCart.addPlan(planData);
                    shoppingCart.logCart();
                    newPlan.on("click",function(){
                        //remove element
                        $(this).remove();
                        shoppingCart.removePlan(newID);
                        console.log("newID "+newID);
                    });
            }

完整的代码块

    $(document).ready(function() {
        //check local storage 
        //if yes create plan and or feature cart objects
        //populate model
        var cartIDcounter       = 0;
        var localStorageKey     = "vlocalstore234"; 
        var shoppingCart;

        shoppingCart            = shoppingCartMaker({});

        if(localStorage.getItem(localStorageKey)){
            //grab cartModel, clear out local storage, calladdplan ans addfeature in a loop to create htmls objs and data obj
            var cartModel = JSON.parse(localStorage.getItem(localStorageKey));
            localStorage.removeItem(localStorageKey);
            //update cart with saved features and plans
            var i;
            var l                   = cartModel.plans.length;
            var newPlan;
            var newID;
            var planData;
            var id;

            for(i=0;i<l;i++){
                console.log(cartModel.plans[0].name);   
                id                  = cartModel.plans[0].name
                $( "#planView" ).append(planCartObjects[id]);
                    newPlan         = $( this ).find('>:last-child');
                    newID           = "cartObject"+cartIDcounter++;
                    newPlan.attr("id",newID);
                    planData        = $.extend(true,{},planDataObjects[id]); //makes a copy of the data object
                    planData.id     = newID;
                    shoppingCart.addPlan(planData);
                    shoppingCart.logCart();
                    newPlan.live("click",function(){
                        //remove element
                        $(this).remove();
                        shoppingCart.removePlan(newID);
                        console.log("newID "+newID);
                    });
            }       
            l                       = cartModel.features.length;
            for(i=0;i<l;i++){
                console.log(cartModel.features[i].name);    
                id                  = cartModel.features[i].name;
                $("#featureView").append(featureCartObjects[id]);
                newPlan             = $( this ).find('>:last-child');
                newID               = "cartObject"+cartIDcounter++;
                newPlan.attr("id",newID);
                featureData         =  $.extend(true,{},featureDataObjects[id]);
                featureData.id      = newID;
                shoppingCart.addFeature(featureData);
                shoppingCart.logCart();
                newPlan.click(function(){
                    //delete view and remove from model
                    $(this).remove();
                    shoppingCart.removeFeature(newID);
                    console.log("newID "+newID);                    
                    //remove from model

                });
            }
        }

        //Plans drag and drop
        $( "#myPlans span" ).draggable({
            start: function(event, ui) {},
            stop: function(event, ui) {  
                $( "#chooser span" ).css({'top':'0px', 'left':'0px'});
            }
        });
        $( "#planView" ).droppable({
            drop: function( event, ui ) {
                if(ui.draggable.find(".planButton").length == 1){
                    // make unique ID,add ID to last child,add click event last child,add plan to model with plan data and ID 
                    var id      = ui.draggable[0].id; // we use the id to grab the right cart html and cart data
                    var id      = id.substring(0, id.length-6);
                    var newPlan;
                    var newID;
                    var planData;

                    $( this ).append(planCartObjects[id]);
                    newPlan         = $( this ).find('>:last-child');
                    newID           = "cartObject"+cartIDcounter++;
                    newPlan.attr("id",newID);
                    planData        = $.extend(true,{},planDataObjects[id]); //makes a copy of the data object
                    planData.id     = newID;
                    shoppingCart.addPlan(planData);
                    shoppingCart.logCart();
                    newPlan.click(function(){
                        //remove element
                        $(this).remove();
                        shoppingCart.removePlan(newID);
                        console.log("newID "+newID);
                    });
                }
            }
        });

        //features drag and drop
        $("#addOnFeatures span").draggable({
            start: function(event, ui){},
            stop: function(event, ui){
                $("#addOnFeatures span").css({'top':'0px', 'left':'0px'});
            }
        });
        $("#featureView").droppable({
            drop: function(event, ui){
                if(ui.draggable.find(".featureButton").length == 1){
                    var id          = ui.draggable[0].id;
                    var id          = id.substring(0, id.length-6);
                    var newPlan;
                    var newID;
                    var featureData;
                    var mydata;

                    $( this ).append(featureCartObjects[id]);
                    newPlan         = $( this ).find('>:last-child');
                    newID           = "cartObject"+cartIDcounter++;
                    newPlan.attr("id",newID);
                    featureData     =  $.extend(true,{},featureDataObjects[id]);
                    featureData.id  = newID;
                    shoppingCart.addFeature(featureData);
                    shoppingCart.logCart();
                    newPlan.click(function(){
                        //delete view and remove from model
                        $(this).remove();
                        shoppingCart.removeFeature(newID);
                        console.log("newID "+newID);                    
                        //remove from model

                    });
                }
            }
        });
    });

3 个答案:

答案 0 :(得分:1)

我认为你的问题在于你的选择器之前的$(this)。 $(this)在.ready()范围内引用了什么?

答案 1 :(得分:1)

这是你的问题。

.on之所以有效,是因为 事件委托给 已经 的元素,就像dom加载后未插入的文档,正文或某些静态父元素,以及基于FIRST参数(单击,模糊等)对该元素执行操作时,它会要求检查 第二个参数 功能或有效的选择器。

newPlan.on("click",function(){
    .... 
})

应该是

$someParentElement.on("click", '.newPlanSelector', function(){
    .... 
})

这是因为事件不能绑定到不存在的元素。如果绑定某些事件,然后添加该元素,则所有事件都将无效。解决这个问题的方法是绑定到静态元素。

由于事件从点击的元素冒泡,向上通过DOM树,它们在上升的过程中击中每个节点。此事件将包含源元素信息(类/ id / etc)。现在,这很好,因为如果我们不确定它是否存在(或者即使我们尝试),我们也不能直接告诉不存在的元素在点击时该怎么做但我们可以告诉该对象的静态父节点当它从指定目标(列表项,链接等)收到某种类型的事件(点击,模糊等)时执行。

活动授权是官方用语。

快乐狩猎!:)

更新另外,请确保您不要使用($(this))作为A.A.发布,这通常是一个问题。使用$ .proxy(function(){})并调用REAL值。

这个。$ someParent是好的对象命名:) this.someParent是坏对象命名:)

只是一些随机提示。不要指望接受这个问题的答案:P

答案 2 :(得分:0)

必须在选择器上设置实时事件绑定,以便在动态创建新div时将其附加到click事件。您正在执行$ .find(),它只会在当前元素中搜索,并将click事件附加到找到的元素。您的问题的解决方案是在选择器上使用“$ .live()”附加click事件。