簡體   English   中英

在閉包 scope 中保存變量

[英]Saving a variable in the closure scope

我有以下內容:

var Save = $('th:first')[0];

$('th').click(function() {
    if (Save !== this) {
        Save = this;
        ...
    }
});

如何將“保存”放入閉包 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 .

(function($) {
    // ....
})(jQuery);

scope 中的任何變量,例如您的var Save ,然后在一個閉包中不在全局名稱 scope 之外。

我真的不明白為什么你想做你想做的事情(或者甚至你到底想做什么......),但對於我認為的問題,這里有兩個解決方案:

var Save = $('th:first')[0];

$('th').each(function() {
   var last = Save;
   $(this).click(function() {
      if (last !== this) {
         last = this;
          ...
      }
   });
});

var Save = $('th:first')[0];

$('th').data('Save', Save).click(function() {
    if ($(this).data('Save') !== this) {
        $(this).data('Save', this);
        ...
    }
});

**編輯**

如果您想要的只是“屏蔽”變量Save ,那么

(function() {

var Save = $('th:first')[0];

$('th').click(function() {
    if (Save !== this) {
        Save = this;
        ...
    }
});

})();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM