第二个事件处理程序无法访问jQuery中第一个事件处理程序中的全局变量?

时间:2015-07-28 04:01:34

标签: events scope global

正如您在下面的代码片段中看到的,selectedImageName变量在第一个事件处理程序中被定义为全局变量。可以通过代码片段底部的函数afterRemoving()来访问此全局变量,但第二个事件处理程序无法访问此全局变量,因此,它会输出错误: Uncaught ReferenceError:selectedImageName is未定义你能解释一下发生了什么吗?我该如何处理这个问题?

JS:

$(document).ready(function() {

    // There are some codes... 

    $(document).ajaxSuccess( function() {

        $("#imgOutput .removeInlineImage").on("click", function(){  

            selectedImageName = $(this).prev().val();
--------------------^ (Everything is OK.)

            optionsRemove = {
                url: 'bilesenler/ajaxRemoveImage.php?imgName=' + selectedImageName,
                beforeSubmit: beforeRemoving,  // pre-submit callback 
                success: afterRemoving,  // post-submit callback 
                resetForm: false        // reset the form after successful submit 
            };

            imgDelete = true;
            $("#addText").submit();
        });


        $("#imgOutput #imgName").on("keypress", function(){

            optionsUpdate = {
                url: 'jx.php?oldImgName=' + selectedImageName + '&newImgName=' + $(this).val(),
----------------------------------------------------^ (Trouble: Uncaught ReferenceError: selectedImageName is not defined)

                beforeSubmit: beforeUpdating,  // pre-submit callback 
                success: afterUpdating,  // post-submit callback 
                resetForm: false        // reset the form after successful submit 
            };

            imgUpdate = true;
            $("#addText").submit();
        });
    });
});

// There are some codes...

function afterRemoving(responseText){
    var temp = selectedImageName.split(".");
-----------------------^ (Everything is OK)

    selectedImageNameWithoutExtension = temp[0];

    $('#imgOutput #' + selectedImageNameWithoutExtension).hide();

    imgDelete = false;

}

1 个答案:

答案 0 :(得分:0)

除非触发click事件,否则selectedImageName为null。单击进程后,将初始化selectImageName。