2015-02-11 127 views
-1
$('.myclass').click(function({ 
    that = $(this); 
    standardDelay = setInterval(function() { 
     doSomething(that.attr("id")); 
    }, 1000); 
}); 

是否可以在其他js文件中訪問全局變量that?如果是的話我怎麼能通過$(this)到我的setInterval函數?js混淆的全局變量

+0

你的代碼將做到這一點了。 – Quentin 2015-02-11 09:39:05

+0

'that'應該已經可以在setInterval中訪問。 – Farhan 2015-02-11 09:39:38

+0

使用var that = $(this)在click函數中初始化它;所以它不能在外部點擊功能 – V31 2015-02-11 09:39:55

回答

0

在Javascript中,與var初始化的變量是本地到當前碼塊(並且是從內碼塊可訪問的)

而不var初始化變量是全球性的,並且可以在任何地方訪問,以及應避免的,除非你真的想這樣做,

所以,你的代碼可以寫成這樣:

$('.myclass').click(function({ 
    var that = $(this); 
    var standardDelay = setInterval(function() { 
     doSomething(that.attr("id")); // You can still access `that` here 
    }, 1000); 
})); 
// No, `that` is `undefined` here