0

我正在尝试向 javascript 添加额外的初始值,以便在通过鼠标在网页内拖动对象时使用。

当我尝试使用刚刚初始化的全局变量时,出现以下错误:

“未定义未捕获的 ReferenceError 前缀PicSlot

当我进入由 mouseup/down 事件调用的拖动函数时,这些变量是可访问的——它们似乎在初始化函数中不可用。

这是被调用的初始化代码:

initialize:function()
{

    this.getJsonParams()
    this.getPicnVidImageParams()
    document.onmousedown=this.drag      // Manages when the mouse is down and dragging 
    document.onmouseup=this.videoslot   // Manages when the dragging has been stopped
    $(document).on("change", "form", this.formChange)
    $(document).on("click", "button", this.selectButton)

}, //initialize

顾名思义,getJsonParams 从服务器获取参数并且工作正常。

getPicnVidParams 是刚刚添加的新初始函数,它使用 getJsonParams 中的变量设置来创建要在鼠标事件中使用的新变量。当我把它放在 this.drag 函数中时,这个函数可以正常工作,但只在开始时调用一次而不是每次鼠标事件调用它更有效。

这是来自 getJsonParams 的一段代码,它创建了 getPicNvidParams 中使用的变量并且工作正常:

//Get Admin data....                     
jsAdmin = $.ajax("getJsAdmin" )
.done(function(data, textStatus, jsAdmin) { 
    // Success !!!
    var tmpText = jsAdmin.responseText.replace("[", "")
    tmpText = tmpText.replace("]", "")          
    admin = JSON.parse( tmpText)            
    vidPreviewHtml = admin.vidPreviewHtml
    debugStatus = admin.jsDiagnostics                        
    prefixPicSlot = admin.prefixPicSlot                      
    prefixVidSlot = admin.prefixVidSlot                      
})
.fail(function() { alert("getJsAdmin - error"); })

这里 getPicnVidParams 的第一部分代码在第一部分失败

非注释行 - firstPicSlot = prefixPicSlot + "0" ...

getPicnVidImageParams:function(e){   

// get the important image params from the first picture and 
// video slots display

firstPicSlot = prefixPicSlot + "0"
firstPicSlotElem=document.getElementById(firstPicSlot.toString())
firstPicInnerHTML = firstPicSlotElem.innerHTML
firstPicSlot = "#" + firstPicSlot

firstVidSlot = prefixVidSlot + "0"
firstVidSlotElem=document.getElementById(firstVidSlot.toString())
firstVidInnerHTML = firstVidSlotElem.innerHTML
firstVidSlot = "#" + firstVidSlot

try{ picWidth = $(firstPicSlot).children("img").attr("width")}
catch(err)
{
    alert("FN: getPicnVidImageParams error (picWidth)" 
        + " \n"  +
        " firstPicSlot: "+ firstPicSlot
    ) 
}                                                                           

奇怪的是,这些初始化函数中的全局变量设置无法访问,但它们的设置却可以在鼠标事件驱动函数中看到。

我正在使用 Chrome。

4

2 回答 2

1

您的问题是 AJAX 是异步的,因此this.getPicnVidImageParams()实际上是在getJsonParams()分配变量之前调用的。您需要将ajax 调用放在函数this.getPicnVidImageParams()的末尾。.done

于 2013-08-13T15:21:12.060 回答
0

您的 ajax 调用getJsonParams是异步的(ajax 中的第一个“a”),这意味着您的 javascript 程序将在后台发出 HTTP 请求时继续执行。基本上,getPicnVidImageParams在 HTTP 请求完成之前调用。将getPicnVidImageParams调用移至 ajax 成功处理程序(done函数)将为您提供所需的结果。

于 2013-08-13T15:23:05.240 回答