简体   繁体   English

Javascript封闭作用域问题

[英]Javascript closure scoping issue

I'm trying to get a reference to cell and it appears null. 我正在尝试获取对cell的引用,它似乎为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: 更新:这是显而易见的,但是我问这个的原因是因为如果您有:cell.pageX将是未定义的:

$('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.
});

The context of the event handler is set to the element that triggered the event. 事件处理程序的上下文设置为触发事件的元素。 You can get at it this way: 您可以通过以下方式获得它:

$('td[someAttr]').mouseenter(function() {
    var cell = this;
    var timeoutId = setTimeout(function() {
        alert(cell.tagName);
    }, 1000);
});

You may also want to wrap it as a jQuery object as well: var cell = $(this); 您可能还希望将其包装为jQuery对象: var cell = $(this);

UPDATE: The first argument is the event object, not the element. 更新:第一个参数是事件对象,而不是元素。 The element is set as the context of the callback (ie this) and you can get access to the event object in exactly the way that you were in your example: 将该元素设置为回调的上下文(即this),您可以按照示例中的方式完全访问事件对象:

$('td[someAttr]').mouseenter(function(event) {
    var cell = this;
    var timeoutId = setTimeout(function() {
        alert(cell.tagName + ' ' + event.pageX);
    }, 1000);
});

Note that the "cell" element is also accessible as "event.target". 注意,“单元”元素也可以作为“ event.target”访问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM