Javascript 闭包作用域问题
我试图获取对单元格的引用,但它显示为空。 如果我理解正确,我应该能够引用该变量。 正确的?
$('td[someAttr]').mouseenter(function(cell) {
var timeoutId = setTimeout(function() {
// what should variable cell be?
}, 1000);
});
或
$('td[someAttr]').mouseenter(function(cell) {
var timeoutId = setTimeout(function() {
// what should variable cell be?
}, 1000, cell);
});
更新:这是显而易见的,但我问这个的原因是因为如果你有:cell.pageX 将是未定义的:
$('td[someAttr]').mouseenter(function() {
var cell = this; //
var timeoutId = setTimeout(function() {
alert(cell.pageX); // cell.pageX will return null
}, 1000);
});
但是,如果你有:
$('td[someAttr]').mouseenter(function(cell) {
alert(cell.pageX); // works fine as cell.pageX will have correct value.
});
I'm trying to get a reference to cell and it appears null. If I'm understanding it correctly, I should be able to reference the variable. Correct?
$('td[someAttr]').mouseenter(function(cell) {
var timeoutId = setTimeout(function() {
// what should variable cell be?
}, 1000);
});
OR
$('td[someAttr]').mouseenter(function(cell) {
var timeoutId = setTimeout(function() {
// what should variable cell be?
}, 1000, cell);
});
UPDATE: This was obvious but the reason I asked this was because cell.pageX would be undefined if you had:
$('td[someAttr]').mouseenter(function() {
var cell = this; //
var timeoutId = setTimeout(function() {
alert(cell.pageX); // cell.pageX will return null
}, 1000);
});
However, if you had:
$('td[someAttr]').mouseenter(function(cell) {
alert(cell.pageX); // works fine as cell.pageX will have correct value.
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
事件处理程序的上下文设置为触发事件的元素。 您可以这样理解:
您可能还想将其包装为 jQuery 对象:
var cell = $(this);
更新:第一个参数是事件对象,而不是元素。 该元素被设置为回调的上下文(即 this),您可以按照示例中的方式访问事件对象:
请注意,“cell”元素也可以作为“event.target”访问。
The context of the event handler is set to the element that triggered the event. You can get at it this way:
You may also want to wrap it as a jQuery object as well:
var cell = $(this);
UPDATE: The first argument is the event object, not the element. The element is set as the context of the callback (i.e. this) and you can get access to the event object in exactly the way that you were in your example:
Note that the "cell" element is also accessible as "event.target".