-1

我在多个地方使用以下 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
    })
}
4

1 回答 1

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
    });
}

是的,您可以使用三元运算符对代码进行更多优化,但这会使代码更难阅读。

于 2013-03-10T14:53:50.267 回答