如何在下面定义这个变量?

时间:2012-05-14 16:40:23

标签: javascript jquery

我有一个取消按钮,当用户上传文件时会出现该按钮。如果用户希望取消文件上传,则可以通过单击取消按钮来向用户显示取消消息。

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

以下是显示2个功能的代码:

startImageUpload函数:

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

stopImageUpload函数:

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

3 个答案:

答案 0 :(得分: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/>';

答案 1 :(得分:0)

您已经将值作为第二个参数传递给“stopImageUpload”,“imagefilename”。只需使用它。

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

答案 2 :(得分: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.
    };
})();