jQuery设置全局变量

时间:2013-03-10 14:49:31

标签: javascript jquery

我在多个地方使用以下JS代码;

$(this).attr("name")

我在差异地方使用它作为;

var currentKey = $(this).attr("name");
currentKeyVal = retrievedUserDataObj[$(this).attr("name")];
currentKeyVal = UserDataObj[$(this).attr("name")];

现在我的问题是有可能以某种方式将其作为全局变量,以便上述代码不会重复吗?

由于$(this),我不确定它是否可以成为gloabl?

修改 实际/优化代码;

    function setFormFieldValues()
{
var currentKey,currentKeyVal;
    if (supports_html5_storage())
    {
    var retrievedUserDataObj = JSON.parse(localStorage.getItem('UserDataObj'));
    localStorageSupport = true;
    }

    $(".formFieldUserData").each(function(){
        var $this = $(this);
        currentKey = $this.attr("name");
        currentKeyVal = UserDataObj[currentKey]; //Set with default values initially

        if (localStorageSupport)
        {
            if(retrievedUserDataObj) //called when there are some values in localStorage
                currentKeyVal = retrievedUserDataObj[currentKey];
        }
        else
        {
            if ($this.val() != "")
                currentKeyVal = $this.val();
        }

        $("#"+currentKey).val(currentKeyVal); //Input text box
        $("#"+currentKey+"Txt").html(currentKeyVal); // Form label
    })
}

1 个答案:

答案 0 :(得分:0)

使用函数进行处理可能更容易;我不确定为什么currentKeyVal定义了两次:

// define outside the function to make them global
var currentKey, currentKeyVal;

function getCurrentKeys(element){
    currentKey = $(element).attr("name");
    currentKeyVal = retrievedUserDataObj[currentKey];
    currentKeyVal = UserDataObj[currentKey];
}

按如下方式使用:

getCurrentKeys(this);

更新添加评论中描述的优化:

function setFormFieldValues()
{
    var currentKey,currentKeyVal;
    if (supports_html5_storage())
    {
    var retrievedUserDataObj = JSON.parse(localStorage.getItem('UserDataObj'));
    localStorageSupport = true;
    }

    $(".formFieldUserData").each(function(){
        var $this = $(this);
        currentKey = $this.attr("name");
        currentKeyVal = UserDataObj[currentKey]; //Set with default values initially

        if (localStorageSupport)
        {
            if(retrievedUserDataObj) //called when there are some values in localStorage
                currentKeyVal = retrievedUserDataObj[currentKey];
        }
        else
        {
            if ($this.val() != "")
                currentKeyVal = $this.val();
        }

        $("#"+currentKey).val(currentKeyVal); //Input text box
        $("#"+currentKey+"Txt").html(currentKeyVal); // Form label
    });
}

是的,您可以使用ternary operators对代码进行更多优化,但这样会使搜索更加困难。