【问题标题】:IE errors with jQuery & timeout带有 jQ​​uery 和超时的 IE 错误
【发布时间】:2014-01-27 21:36:58
【问题描述】:

在 jquery 悬停事件中,我使用以下代码下拉菜单:

clearTimeout(hTimeout);
$('#lowermenu').queue('fx', []);
$('#menucenter .current').removeClass('current');
$(this).children('a').addClass('current');        
dTimeout = setTimeout(function($item){slidelower($item)}, 200, $(this)); // This is the bad line

function slidelower($li)
{
    $li.addClass('dropping');
    $lowermenu = $li.children('ul').clone();
    $('#lowermenu:not(:animated)').empty().append($lowermenu).slideDown();
    $('#lowermenu > ul > li:not(:animated)').hover(function()
    {                      
        $(this).children('ul:hidden').css('top', 'auto').slideDown();
    }, function()
    {
        $(this).children('ul:visible').slideUp();
    });
}

我收到以下错误:

网页错误详情

用户代理:Mozilla/4.0(兼容;MSIE 8.0;Windows NT 5.1;Trident/4.0;GTB6.3;.NET CLR 1.1.4322;.NET CLR 2.0.50727;.NET CLR 3.0.4506.2152;.NET CLR 3.5.30729;OfficeLiveConnector.1.3;OfficeLivePatch.0.0) 时间戳:2009 年 11 月 14 日星期六 11:12:46 UTC

消息:'undefined' 为 null 或不是对象

行:81

字符:25

代码:0

URI:[网址在这里]

我怀疑它是由 setTimeout 引起的 - 我传入了第三个参数作为匿名函数的参数。该匿名函数调用带有闭包的函数。

谁能帮忙?

【问题讨论】:

    标签: javascript jquery internet-explorer-8 internet-explorer-7 settimeout


    【解决方案1】:
    $(this).children('a').addClass('current');   
    var that = this;     
    dTimeout = setTimeout(function($item){slidelower($item)}, 200, that); // This is the bad line
    

    setTimeout 归window 对象所有,因此this 指的是window。通过使用 'that' 变量缓存它来保存对外部上下文的引用。

    【讨论】:

    • 感谢 meder,您的回答有所帮助,但我无法传递可用的对象,甚至尝试了该方法的许多排列。不过,谢谢。
    • 好吧,我还是有问题:setTimeout(function(theid){window.console.log(theid)}, 200, 'test');这是输出到控制台“未定义”。我做错了什么?
    • 超时调用没有参数,所以没有theid被传递到你的函数中,因此它是undefined。您需要使用闭包来保留变量的副本,或 function.bind(将来或现在使用适当的原型黑客)。
    【解决方案2】:

    好的,我发现了问题。 IE中的setTimeout不支持附加参数:

    https://developer.mozilla.org/en/window.setTimeout

    任务中止。

    【讨论】:

      【解决方案3】:

      以防万一其他人读到这个: 尽管在 OP 概述的方法中无法将参数传递给 IE 中的 setInterval 或 setTimeout。可以通过使用匿名函数并传入范围内的参数来做到这一点。

      所以 OP 需要将坏行替换为:

      dTimeout = setTimeout(function(){slidelower($item)}, 200);
      

      这是 IE 中 setTimeout 的预期语法(2 个参数:函数和延迟),但匿名函数会将 $item 的值传递给“slidelower”

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-02-27
        • 1970-01-01
        • 2016-11-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-26
        相关资源
        最近更新 更多