我在多个地方使用以下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
})
}
我想你可以这样做'window.foo = $(this)'。但js中的'this'真的不同。我认为你需要提供更多的上下文。 – jagttt 2013-03-10 14:52:35
鉴于'this'的上下文取决于代码中的位置,将它变为全局变量有什么意义?这只会在不太可能发生的情况下有意义,即this在任何情况下都指向*非常相同的元素。 – Boaz 2013-03-10 14:52:36