2016-06-27 22 views
1

如何訪問JavaScript中內部函數的閉包變量。如何在JavaScript中使用Closure Scope訪問變量

我要訪問setTimeout功能UL變量。

ul.find("li").each(function (a, ele) { 

     $(ele).attr("tabindex", options.items[a].tabindex); 

     $(ele).on("focusout", function() { 

      setTimeout(function() { 
       **//ACCESS UL HERE** 
       debugger; 
      }, 1); 

     }.bind(ul,ele)); 
    }.bind(ul)); 

回答

1

setTimeout

Closures使用closure '記住' 它們被創建的環境。

ul.find("li").each(function(a, ele) { 
    $(ele).attr("tabindex", options.items[a].tabindex); 
    $(ele).on("focusout", function() { 
     setTimeout(function(ul) { 
     return function() { 
      console.log(ul); 
     } 
     })(ul), 1); 
    }.bind(ul, ele)); 
}.bind(ul)); 
+0

@ShanKhan,我就寧可不回答;)你想了解雙方'Closures'以及'#功能來bind'使任何舉動..都有完全不同的目的..;) – Rayon

+0

你能給我一個很好的鏈接,提供了一個根本不同的目的,所以我可以理解,我見過的例子,但這些都可以由兩個執行。 –

0

它正常工作。 ul的範圍在setTimeout函數內有效。

ul.find("li").each(function() { 
    $(this).attr("tabindex", options.items[a].tabindex) 
    .on("focusout", function() { 
     setTimeout(function() { 
     ul.css('color', 'orange'); 
     }, 1); 
    }); 
}); 

這樣一個簡單的代碼將解釋:

(function s() { 
 
    var a = "hi"; 
 
    setTimeout(function() { 
 
    console.log(a); 
 
    }, 1000); 
 
})();

這裏,ul是一樣的a變量。

0

您可以通過查找當前元素的父級來使用UL。爲了得到與特定類型的直接父,你可以使用.closest()方法

$(ele).on("focusout", function() { 
    var el = $(this); 
    setTimeout(function() { 
    el.closest("ul"); 
    debugger; 
    }, 1); 

}.bind(ul, ele)); 
相關問題