我正在创建一个简单的图像drag-n-drop jquery扩展。它的作用是你拖动一个文件并显示文件的预览,然后返回一个带有文件名的对象和要通过ajax POST发送的图像数据。
(function($) {
$.fn.dnd = function()
{
jQuery.event.props.push('dataTransfer');
$(this).bind('drop',function(e){
var files = e.dataTransfer.files;
var $preview = $(this);
var result = [];
if(files.length > 1)
{
$(this).html('One file only');
return false;
}
if(files[0].type === 'image/png' ||
files[0].type === 'image/jpeg' ||
files[0].type === 'image/ppeg')
{
var fileReader = new FileReader();
fileReader.onload = (function(f)
{
return function(e)
{
result.push({name:f.name,value:this.result});
$preview.removeAttr('style');
$preview.html('<img src="'+ this.result +'" width="80%"/>');
};
})(files[0]);
fileReader.readAsDataURL(files[0]);
}
else
{
$(this).html('images only. GIF not allowed.');
return false;
}
e.preventDefault();
return result;
});
};
}(jQuery));
我以这种方式执行代码。
$(document).ready(function(){
var result = $('#ec-drag-n-drop').dnd();
console.log(result);
}
当我查看控制台时,它返回'undefined'。我错过了什么吗?
答案 0 :(得分:0)
您不会返回结果。
此代码:
e.preventDefault();
return result;
在回复$(this).bind('drop')
内发生。
因此,您需要通过自己的插件提供回调:
$.fn.dnd = function(callback)
{
jQuery.event.props.push('dataTransfer');
$(this).bind('drop',function(e){
// Your code
callback(result);
}
}
在您的主页中:
$(document).ready(function(){
$('#ec-drag-n-drop').dnd(function(result) {
console.log(result);
});
}