问题
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