2013-03-10 143 views
-1

我在多个地方使用以下JS代码;jQuery设置全局变量

$(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 
    }) 
} 
+0

我想你可以这样做'window.foo = $(this)'。但js中的'this'真的不同。我认为你需要提供更多的上下文。 – jagttt 2013-03-10 14:52:35

+0

鉴于'this'的上下文取决于代码中的位置,将它变为全局变量有什么意义?这只会在不太可能发生的情况下有意义,即this在任何情况下都指向*非常相同的元素。 – Boaz 2013-03-10 14:52:36

回答

0

只用一个函数来做这个处理可能更容易;我不知道为什么currentKeyVal被定义了两次:在注释中描述

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

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

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

如下使用它,您可以使用更多地优化代码0,但这会让阅读变得更加困难。

+0

Thx ...我已经用实际的代码编辑了原始问题....所以你可以更好地理解为什么我已经完成了我编码的方式... – testndtv 2013-03-10 15:02:59

+0

嗯,我看到你可以做两个优化:(1)'.each()'函数中的第一行可能是'var $ this = $(this)',并且使用它而不是重复定义这个jQuery对象。 (2)使用'currentKey'而不是'$(this).attr(“name”);'多次像我在上面的代码示例中所做的那样。 – Mottie 2013-03-10 15:11:56

+0

你可以请编辑我原来的问题,以便我可以更好地理解优化...同样你也可以建议任何额外的优化,以及... – testndtv 2013-03-10 15:15:27