【发布时间】:2023-03-04 22:50:01
【问题描述】:
我在多处使用下面的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
})
}
【问题讨论】:
-
我认为你可以做到这一点
window.foo = $(this)。但是 js 中的this确实不一样。我认为您需要提供更多背景信息。 -
鉴于
this的上下文会根据代码中的位置而变化,将其设为全局变量有什么意义?这只有在this在任何上下文中引用 very same 元素这一不太可能发生的情况下才有意义。
标签: javascript jquery