jQuery .on()事件不适用于动态添加的元素 [英] jQuery .on() event doesn't work for dynamically added element

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

问题描述

我正在制作一个项目,当用户点击一个按钮时,动态插入带有按钮的整个div,在该div内部有一个按钮,当用户点击它时,它会执行其他操作,例如提醒某些内容例。



问题是当我在动态添加的div中按下该按钮时,没有任何反应。事件根本没有触发。



我尝试在HTML中添加该div,然后再次尝试,事件工作。所以我猜这是因为div是动态添加的。



添加的div有一个类 mainTaskWrapper ,按钮有一个类 checkButton
该事件是在 script.js 下面的 .on() / p>

这是我的代码:



helper_main_task.js:(这是添加的对象div,你不必阅读它,因为我认为这是所有关于div被动态添加,但我会把它,以防万一你需要)

  var MainUtil = {
tasksArr:[],
catArr:[all],
add:function(){

var MTLabel = $(#mainTaskInput)。val(),//任务标签
MTCategory = $(#mainCatInput)。val(),//任务类别
MTPriority = $(#prioritySlider)。slider(value)//任务优先级
MTContents = $('< div class =wholeTask> \
< div class = mainTaskWrapper clearfix> \
< div class =mainMarker>< / div> \
< label class =mainTaskLabel>< / label> \
< div class =holder>< / div> \
< div class =subTrigger >< / div> \
< div class =checkButton>< / div> \
< div class =optTrigger>< / div> \\
< div class =addSubButton>< / div> \
< div class =mainOptions> \
< ul> \
< li id =mainInfo>细节< / li> \
< li id =mainEdit>编辑< / li> \
< li id = mainDelete>删除< / li> \
< / ul> \
< / div> \
< / div> \
< / div>');


this.tasksArr.push(MTLabel);

//设置标签
MTContents.find(。mainTaskLabel)。text(MTLabel);

//设置类别
如果(MTCategory ==){
MTCategory =uncategorized;
}
MTContents.attr('data-cat',MTCategory);
if(this.catArr.indexOf(MTCategory)== -1){
this.catArr.push(MTCategory);
$(#categories ul)。append(< li>+ MTCategory +< / li>);
}
$(#mainCatInput)。autocomplete(option,source,this.catArr);

//设置优先级标记颜色
if(MTPriority == 2){
MTContents.find(。mainMarker)。css(background-color,red );
} else if(MTPriority == 1){
MTContents.find(。mainMarker)。css(background-color,black);
} else if(MTPriority == 0){
MTContents.find(。mainMarker)。css(background-color,blue);
}

MTContents.hide();
$(#tasksWrapper)。prepend(MTContents);
MTContents.slideDown(100);

$(#tasksWrapper)。sortable({
axis:y,
scroll:true,
scrollSpeed:10,
scrollSensitivity:10,
句柄:$(。holder)
});

}
};

script.js:(.on()函数的文件位于底部)

  $(function(){
$(#addMain,#mainCatInput)。 on('click keypress',function(evt){
if(evt.type ==click|| evt.type ==keypress){
if((evt.type == click&& evt.target.id ==addMain)||
(evt.which == 13&& evt.target.id ==mainCatInput)){
MainUtil.add();
}
}
});

//这是我在说的事件:
$( div.mainTaskWrapper)。on('click','.checkButton',function(){
alert(test text);
});
});


解决方案

看起来不像 div.mainTaskWrapper 存在。



文档(是的,它实际上是粗体):


事件处理程序仅限于当前选定的元素;它们必须存在于您的代码调用 .on()的页面上。为了确保元素存在并可以选择,请执行事件



[...]



通过选择在委托事件处理程序附带时确保存在的元素,可以使用委托事件来避免经常附加和删除事件处理程序。


您可能希望将其绑定到 #tasksWrapper

  $(#tasksWrapper)。on('click','.checkButton',function(){
alert(test text);
});


I'm making a project where a whole div with buttons is being inserted dynamically when user click a button, and inside that div there's a button, which when the user click on it, it does something else, like alerting something for example.

The problem is when i press on that button in the dynamically added div, nothing happens. The event doesn't fire at all.

I tried to add that div inside the HTML and try again, the event worked. So i guess it's because the div is dynamically added.

The added div has a class mainTaskWrapper, and the button has a class checkButton. The event is attached using .on() at the end of script.js file below.

Here's my code :

helper_main_task.js : (that's the object that adds the div, you don't have to read it, as i think it's all about that div being dynamically added, but i'll put it in case you needed to)

var MainUtil = {
    tasksArr : [],
    catArr : ["all"],
    add : function(){       

        var MTLabel = $("#mainTaskInput").val(),  //task label  
            MTCategory = $("#mainCatInput").val(), //task category 
            MTPriority = $("#prioritySlider").slider("value"),  //task priority     
            MTContents = $('<div class="wholeTask">\
                                <div class="mainTaskWrapper clearfix">\
                                    <div class="mainMarker"></div>\
                                    <label class="mainTaskLabel"></label>\
                                    <div class="holder"></div>\
                                    <div class="subTrigger"></div>\
                                    <div class="checkButton"></div>\
                                    <div class="optTrigger"></div>\
                                    <div class="addSubButton"></div>\
                                    <div class="mainOptions">\
                                        <ul>\
                                            <li id="mainInfo">Details</li>\
                                            <li id="mainEdit">Edit</li>\
                                            <li id="mainDelete">Delete</li>\
                                        </ul>\
                                    </div>\
                                </div>\
                            </div>');


        this.tasksArr.push(MTLabel);

        //setting label
        MTContents.find(".mainTaskLabel").text(MTLabel);        

        //setting category  
        if(MTCategory == ""){
            MTCategory = "uncategorized";
        }
        MTContents.attr('data-cat', MTCategory);
        if(this.catArr.indexOf(MTCategory) == -1){
            this.catArr.push(MTCategory);
            $("#categories ul").append("<li>" + MTCategory +"</li>");
        }
        $("#mainCatInput").autocomplete("option", "source",this.catArr);

        //setting priority marker color
        if(MTPriority == 2){ 
            MTContents.find(".mainMarker").css("background-color", "red");
        } else if(MTPriority == 1){
            MTContents.find(".mainMarker").css("background-color", "black");
        } else if(MTPriority == 0){
            MTContents.find(".mainMarker").css("background-color", "blue");
        }       

        MTContents.hide();
        $("#tasksWrapper").prepend(MTContents); 
        MTContents.slideDown(100);

        $("#tasksWrapper").sortable({
            axis: "y",
            scroll: "true",
            scrollSpeed : 10,
            scrollSensitivity: 10,
            handle: $(".holder")            
        });

    }
};

script.js : (the file where the .on() function resides at the bottom)

$(function(){
     $("#addMain, #mainCatInput").on('click keypress', function(evt){       
        if(evt.type == "click" || evt.type =="keypress"){
            if((evt.type =="click" && evt.target.id == "addMain") ||
                (evt.which == 13 && evt.target.id=="mainCatInput")){    
                    MainUtil.add();                                             
            }
        }
    });

    //Here's the event i'm talking about :
    $("div.mainTaskWrapper").on('click', '.checkButton' , function(){
        alert("test text");
    });
});

解决方案

It does not look like div.mainTaskWrapper exist.

From the documentation (yes, it is actually bold):

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page.

[...]

By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers.

You might want to bind it to #tasksWrapper instead:

$("#tasksWrapper").on('click', '.checkButton' , function(){
    alert("test text");
});

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

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