How to bind jquery function to a dynamic DOM

2019-08-08 15:22发布

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.

3条回答
霸刀☆藐视天下
2楼-- · 2019-08-08 15:57

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.

查看更多
SAY GOODBYE
3楼-- · 2019-08-08 16:04

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...

查看更多
老娘就宠你
4楼-- · 2019-08-08 16:13

Use the function's callback

$('.new-variant-image').fileupload({
      dataType: 'script',
     add: function(e, data),
     done: $('.new-variant-image').click(function(){
     })
{
查看更多
登录 后发表回答