2015-02-11 128 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