对javascript / jquery变量范围感到困惑

时间:2013-01-25 10:25:00

标签: javascript jquery

下面代码中的pastPath变量令我困惑。我通常使用C#和MVC,这当然意味着我使用HTML,JavaScript和JQuery以及其他相关的Web /移动技术。

当我运行此代码并单击.moreBtn pastPath报告时,它会按照我的意图设置为URL。然而,当我尝试使用.backBtn来设置URL并强制我的浏览器返回上一页时,我得到了pastPath未定义,或者它被设置为hello。

我知道我在这里理解范围时遇到了问题。我已阅读有关JavaScript范围的文章,但我想知道是否有人可以解决此问题并解释我如何从第一个函数到第二个函数获取我的URL。

稍后我会在JavaScript中阅读有关范围的更多内容,但在大多数其他语言中,它的范围似乎非常不同,而且我现在没有时间正确地研究它。

$(document).ready(function ()
{
    pastPath = "hello";

    $(".moreBtn").click(function ()
    {
        var controller = $(".moreBtn").data('ctrl');
        var action = $(".moreBtn").data('action');
        loc = GetPathDetails("full"); //This simply returns the part of the URL I need.
        pastPath = loc;
        alert(pastPath);
        var fullPath = loc + "/" + controller + "/" + action;
        window.location = fullPath;
    });

    $(".backBtn").click(function ()
    {
        alert(pastPath);
        //window.location = pastPath;
    });

});

感谢您的帮助。

4 个答案:

答案 0 :(得分:4)

.moreBtn点击会更改页面,因此您存储在pastPath中的所有数据都将丢失。

查看dom存储空间,https://developer.mozilla.org/en-US/docs/DOM/Storage

答案 1 :(得分:1)

  • 当您使用jQuery时,在单击(或其他事件)处理程序中, 'this'将引用触发事件的DOM元素。

  • 如果您没有使用“var pastPath”声明变量,那么pastPath将是一个“全局变量”,这意味着它将是全局对象的属性。

在您的点击处理程序中,无论您是访问this.pastPath还是仅pastPath,都不会访问相同的变量(除非this引用全局对象,但它不是因为它由jQuery在您单击的特定DOM元素上触发)。

答案 2 :(得分:1)

当你点击$(“。moreBtn”)时,它会将你重定向到fullpath并再次重定向设置pastPath =“hello”,所以如果你想在下一页上找到pastpath值,请将它作为querystring发送然后将它用于你的后门。

类似的东西:

    $(document).ready(function ()
    {
       var pastPath = "hello";

        $(".moreBtn").click(function ()
        {
        var controller = $(".moreBtn").data('ctrl');
        var action = $(".moreBtn").data('action');
        loc = GetPathDetails("full"); //This simply returns the part of the URL I need.
        pastPath = loc;
        alert(this.pastPath);
        var fullPath = loc + "/" + controller + "/" + action + " ?pastpath="+loc;
        window.location = fullPath;
        });

        $(".backBtn").click(function ()
        {
                   var path = window.location + ''.split('pathname=');
                   alert(path1[1]);
                });

    });

答案 3 :(得分:0)

我们知道变量有两个范围,即局部范围和全局范围。

全局范围:以简单的术语(但不完全是)在函数外声明或定义的变量。

本地范围:在函数内声明的变量。

所以$(document).ready(function(){});也是一个函数,所以在这之外声明变量将解决问题。但要避免在函数中使用var pastPath,这可能会将该变量用作局部变量。

所以你的最终代码将转向 var pastPath =“hello”; $(document).ready(function(){

$(".moreBtn").click(function() {
    var controller = $(".moreBtn").data('ctrl');
    var action = $(".moreBtn").data('action');
    loc = GetPathDetails("full");
    //This simply returns the part of the URL I need.
    pastPath = loc;
    alert(pastPath);
    var fullPath = loc + "/" + controller + "/" + action;
    window.location = fullPath;
});

$(".backBtn").click(function() {
    alert(pastPath);
    //window.location = pastPath;
});

});

相关问题