ajax打破了我的javascript对象吗?

时间:2009-06-30 19:12:00

标签: asp.net javascript ajax

我有一个使用UpdatePanels执行ASP.NET ajax回发的页面。在一些javascript中,我在window.onload事件中设置了一些对象,效果很好。当我做回发时,似乎我的对象搞砸了。

从表中接收事件的一个对象不再接收事件。我还有一个案例,其中具有对按钮的本地引用的对象将无法更新它们。这是搞砸了的按钮javascript:

function EditItemPage(clientId)
{
    this.saveButton = $get(clientId + ""_{2}"")
    this.publishButton = $get(clientId + ""_{3}"")
    this.exitButton = $get(clientId + ""_{4}"")

    EditItemPage.prototype.GoDirty = function()
    {
        //it works if i add these, but i'd rather not have to.
        this.saveButton = $get(clientId + ""_{2}"")
        this.publishButton = $get(clientId + ""_{3}"")
        this.exitButton = $get(clientId + ""_{4}"")

        this.saveButton.disabled = false;
        this.publishButton.value = 'Save and Publish';
        this.exitButton.value = 'Discard changes and Exit';
    }
}

所以在我做回发之后,按钮引用会搞砸,除非我像在GoDirty()函数中那样重置它们。

有什么见解?

1 个答案:

答案 0 :(得分:2)

this关键字(特殊变量)根据调用它的函数而变化。基本上,这是一个范围问题。您需要围绕在ajax响应上调用的函数执行闭包, OR 将您需要的内容放入全局作用域, OR 执行您正在执行的操作(你不喜欢的。)

编写闭包是“正确”的方式。

您可能熟悉this变量基于表单输入事件更改范围的方式。对于文本框,如果您使用onblur事件,this会引用刚失去焦点的textarea。

See this question for an example of how to do the closure.

This is also another good resource.

(我确信我可以在这里复制并粘贴示例,但这似乎是多余的)

相关问题