How to bind jquery function to a dynamic DOM

烂漫一生 提交于 2020-01-15 10:35:28

问题


I am using jquery file upload function on my page like following:

$('.new-variant-image')
 .fileupload({ 
       dataType: 'script',
       add: function(e, data){ 
       }
});

but the DOM class "new-variant-image" is dynamically created after the page is loaded, so it wouldn't work. I searched ways to bind dynamic event using "on" and "live" but wouldn't get it to work in this case.

Any assistance will be much thanked.

Edit

The DOM element "new-variant-image" is created afterwards using AJAX, it works if I put the code after the element is created. BUT I want to avoid that, because when I call the function using ajax multiple times it cause the browser to hang about 2 to 3 seconds.


回答1:


Use the function's callback

$('.new-variant-image').fileupload({
      dataType: 'script',
     add: function(e, data),
     done: $('.new-variant-image').click(function(){
     })
{



回答2:


Your code $('.new-variant-image').fileupload({ dataType: 'script', add: function(e, data){ should be after the element creation code ....

I don't know how you are creating the element(using ajax or something else)...

What georgi-it has suggested should work...




回答3:


Although very late to answer this question, but as of jQuery 1.7 you can use jQuery.fn.on.

$(document).on("click", ".new-variant-image", function () {
    $('.new-variant-image')
            .fileupload({
                dataType: 'script',
                add: function (e, data) {
                }
            });
})

This attaches event handler function for all present elements or dynamically appended element with class new-variant-image.



来源:https://stackoverflow.com/questions/15860839/how-to-bind-jquery-function-to-a-dynamic-dom

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!