JQuery:创建扩展返回变量未定义

JQuery: Creating Extension return variable undefined

本文关键字:变量 未定义 返回 扩展 创建 JQuery      更新时间:2023-09-26

我正在创建一个简单的图像拖放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);
}

当我查看控制台时,它返回"未定义"。我错过了什么吗?

您不返回结果。

此代码:

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);
   });
}