我正在使用jupery的ocupload插件来允许我的应用程序的用户将图像上传到我的服务器而不刷新页面。通常我没有任何困难,但我试图在点击事件回调中初始化它,它根本不起作用。但是,如果我尝试在点击事件回调函数完成后通过手动将初始化代码输入到我的js控制台来初始化它,它就可以工作了。谁知道我在这里缺少什么?谢谢!
//Open dialog view for profile picture manipulation
jQuery('#admin_profile_picture_img').bind('click', function(){
jQuery('#admin_profile_picture_img_dialog').dialog('open');
//initialize one-click upload for profile picture
window.myUpload = jQuery('#upload_new').upload({
name: 'file',
action: '',
enctype: 'multipart/form-data',
params: {},
autoSubmit: true,
onSubmit: function(){
console.log('onSubmit()');
},
onComplete: function(){
console.log('onComplete()');
},
onSelect: function(){
console.log('onSelect()');
}
});
console.log(window.myUpload);
});
修改:
这是与此问题相关的HTML:
<div style="display:none" id="admin_profile_picture_img_dialog">
<img id="preview_profile_pic" src="http://vibecompass.s3.amazonaws.com/vc-images/profile-pics/c3d9262de038c507a9d86fae67145829.png" alt="profile picture" />
<a id="upload_new" href="#" style="background:#39f; font-size: 24px; color: white;">Click here to upload a photo</a>
编辑2 :
如果我将代码移动到对话框的“open”事件回调中,我会遇到同样的问题。
//initialize dialog for profile picture selection/crop
jQuery('#admin_profile_picture_img_dialog').dialog({
draggable: false,
height: 500,
width: 500,
modal: true,
resizable: false,
autoOpen: false,
title: 'modify profile picture',
open: function(event, ui){
setTimeout(function() {
//initialize one-click upload for profile picture
window.myUpload = jQuery('#upload_new').upload({
name: 'file',
action: '',
enctype: 'multipart/form-data',
params: {},
autoSubmit: true,
onSubmit: function(){
console.log('onSubmit()');
},
onComplete: function(){
console.log('onComplete()');
},
onSelect: function(){
console.log('onSelect()');
}
});
}, 500);
console.log('should open');
}
});
但是,如果我尝试从命令行启动它,它会按预期工作。
答案 0 :(得分:1)
尝试将setTimeout
调用中无效的代码放入1ms延迟。即,
//Open dialog view for profile picture manipulation
jQuery('#admin_profile_picture_img').bind('click', function(){
jQuery('#admin_profile_picture_img_dialog').dialog('open');
setTimeout(function() {
//initialize one-click upload for profile picture
window.myUpload = jQuery('#upload_new').upload({
name: 'file',
action: '',
enctype: 'multipart/form-data',
params: {},
autoSubmit: true,
onSubmit: function(){
console.log('onSubmit()');
},
onComplete: function(){
console.log('onComplete()');
},
onSelect: function(){
console.log('onSelect()');
}
});
}, 1);
console.log(window.myUpload);
});
修改:我的预感是代码中此时尚不存在$("#upload_new")
。它是在对话框的open事件处理程序中创建的吗?我尝试在对话框的open事件处理程序中初始化上传控件。或者,你可以尝试以下方法,这有点极端,但应该工作:
//Open dialog view for profile picture manipulation
jQuery('#admin_profile_picture_img').bind('click', function(){
jQuery('#admin_profile_picture_img_dialog').dialog('open');
initializeUpload();
function initializeUpload() {
var $uploadNew = jQuery("#upload_new");
if ($uploadNew.length == 0) {
setTimeout(initializeUpload, 200);
}
else {
window.myUpload = $uploadNew.upload({
name: "file",
...
});
}
}
}