0

我有一个取消按钮,当用户上传文件时会出现。如果用户希望取消文件上传,那么他们可以通过单击“取消”按钮,它会向用户显示取消消息。

尝试此操作时的唯一问题是,它说明在我要显示消息的 stopImageUpload 函数中未定义 cancel_image_file_name。但我确实在 startImageUpload 函数中定义了这个。所以我的问题是如何从 startImageUpload 函数中获取 cancel_image_file_name 并在 stopImageUpload 函数中定义它?

下面是显示这两个函数的代码:

启动图像上传功能:

var cancelimagecounter = 0;

function startImageUpload(imageuploadform, imagefilename){

    cancelimagecounter++;

            var _cancelimagecounter = cancelimagecounter;

    $('.imageCancel').on("click", function(event) {
        var cancel_image_file_name = $(this).attr('cancel_image_file_name');

    return stopImageUpload(2, cancel_image_file_name);

});       
      return true;
}

停止图像上传功能:

var imagecounter = 0;

function stopImageUpload(success, imagefilename){

      var result = '';
      imagecounter++;

      if (success == 1){
         result = '<span class="imagemsg'+imagecounter+'">The file was uploaded successfully!</span><br/><br/>';      
         $('.listImage').eq(window.lastUploadImageIndex).append('<div>' + htmlEncode(imagefilename) + '<button type="button" class="deletefileimage" image_file_name="' + imagefilename + '">Remove</button><br/><hr/></div>'); 
      }
      else if (success == 2){
          result = '<span class="imageemsg">' + cancel_image_file_name + ' Upload Was Cancelled!</span><br/><br/>';
      }
      else {
         result = '<span class="imageemsg">There was an error during file upload!</span><br/><br/>';
      }


      return true;   
}
4

3 回答 3

4

在 JavaScript 中,变量具有函数级别的作用域,要进入您的其他函数,请在两个函数之外cancel_image_file_name定义它。


顺便说一句,您可以imagefilename从您的stopImageUpload函数中使用,因为您已经将它传递给该函数:

return stopImageUpload(2, cancel_image_file_name);

因此,在您的stopImageUpload函数中,更改行:

result = '<span class="imageemsg">' + cancel_image_file_name + ' Upload Was Cancelled!</span><br/><br/>';

到:

result = '<span class="imageemsg">' + imagefilename + ' Upload Was Cancelled!</span><br/><br/>';
于 2012-05-14T16:43:07.750 回答
0

您已经将值作为第二个参数传递给“stopImageUpload”、“imagefilename”。就用那个。

事实上,在同一个函数的其他地方,您正在使用该参数。

于 2012-05-14T16:44:02.180 回答
0

像这样重构你的代码:

(function() {
    var cancelimagecounter = 0,
        imagecounter = 0,
        cancel_image_file_name;
    window.startImageUpload = function(imageuploadform,imagefilename) {
        ...
            cancel_image_file_name = ... // (remove the var)
        ...
    };
    window.stopImageUpload = function(success,imagefilename) {
        ...
        // cancel_image_file_name is not undefined now.
    };
})();
于 2012-05-14T16:44:25.267 回答