0

シンプルな画像のドラッグ アンド ドロップ jquery 拡張機能を作成しています。1 つのファイルをドラッグすると、ファイルのプレビューが表示され、ファイル名と 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);
}

コンソールを見ると、「未定義」が返されます。何か不足していますか?

4

1 に答える 1

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);
   });
}
于 2013-11-05T07:55:53.287 に答える