[英]Saving a variable in the closure scope
I have the following:我有以下内容:
var Save = $('th:first')[0];
$('th').click(function() {
if (Save !== this) {
Save = this;
...
}
});
How do I put "Save" into a closure scope?如何将“保存”放入闭包 scope?
With jQuery, I tend to wrap the whole lot in a function, that passes in the jQuery
object as $
, to avoid namespace clashes on that shorthand, as recommended by the jQuery documentation . With jQuery, I tend to wrap the whole lot in a function, that passes in the jQuery
object as $
, to avoid namespace clashes on that shorthand, as recommended by the jQuery documentation .
(function($) {
// ....
})(jQuery);
Any variables within that scope, for instance your var Save
, are then out of the global name scope, in a closure. scope 中的任何变量,例如您的var Save
,然后在一个闭包中不在全局名称 scope 之外。
I don't really understand why you want to do what you're trying to do (or even what exactly you're trying to do...), but here are two solutions to what I think the question is about:我真的不明白为什么你想做你想做的事情(或者甚至你到底想做什么......),但对于我认为的问题,这里有两个解决方案:
var Save = $('th:first')[0];
$('th').each(function() {
var last = Save;
$(this).click(function() {
if (last !== this) {
last = this;
...
}
});
});
and和
var Save = $('th:first')[0];
$('th').data('Save', Save).click(function() {
if ($(this).data('Save') !== this) {
$(this).data('Save', this);
...
}
});
** EDIT ** **编辑**
Of if what you want is just "shield" the variable Save
, then如果您想要的只是“屏蔽”变量Save
,那么
(function() {
var Save = $('th:first')[0];
$('th').click(function() {
if (Save !== this) {
Save = this;
...
}
});
})();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.