有人能告诉我为什么这会出错吗?

我将代码移动到函数中以允许我延迟它所以它不那么敏感(变得烦人)

未捕获的 ReferenceError: hideleftnav 未定义

未捕获的 ReferenceError:未定义 showleftnav

 function showleftnav()
    {
        $(".leftnavdiv").css('width','500px');
        $("body").css('padding-left','510px');
        //get measurements of window
        var myWidth = 0, myHeight = 0;
        if( typeof( window.innerWidth ) == 'number' ) {
            //Non-IE
            myWidth = window.innerWidth;
            myHeight = window.innerHeight;
        } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
            //IE 6+ in 'standards compliant mode'
            myWidth = document.documentElement.clientWidth;
            myHeight = document.documentElement.clientHeight;
        } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
            //IE 4 compatible
            myWidth = document.body.clientWidth;
            myHeight = document.body.clientHeight;
        }
        $('#maindiv').width(myWidth - 540);
    }

    function hideleftnav()
    {
        $(".leftnavdiv").width(10);
        $("body").css('padding-left','20px');
        //get measurements of window
        var myWidth = 0, myHeight = 0;
        if( typeof( window.innerWidth ) == 'number' ) {
            //Non-IE
            myWidth = window.innerWidth;
            myHeight = window.innerHeight;
        } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
            //IE 6+ in 'standards compliant mode'
            myWidth = document.documentElement.clientWidth;
            myHeight = document.documentElement.clientHeight;
        } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
            //IE 4 compatible
            myWidth = document.body.clientWidth;
            myHeight = document.body.clientHeight;
        }
        $('#maindiv').width(myWidth - 50);
    }

    $(".leftnavdiv").live({                                          //code for autohide
        mouseenter:
        function () {
            setTimeout("showleftnav()", 5000);
        },
        mouseleave:
        function () {
            setTimeout("hideleftnav()", 5000);
        }
    });

最佳答案

看起来您发现使用带有字符串的 setTimeout 作为第一个参数的一个问题。这是一个说明相同问题的浓缩示例:

(function() {
    function test() {
        console.log('test');
    }

    setTimeout('test()', 500);  // ReferenceError: test is not defined
    setTimeout(test, 500);      // "test"
    setTimeout(function() {     // "test"
        test();
    }), 500);
})();

演示:http://jsfiddle.net/mXeMc/1/

使用字符串会导致您的代码使用 window 上下文进行评估。但是由于您的代码在回调函数中,因此无法从 test 访问 window ;它是私有(private)的,只限于匿名函数的范围。

仅使用 test 引用函数可避免此问题,因为您直接指向函数而不使用 eval

关于javascript - settimeout 给出未捕获的 ReferenceError : function is not defined,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14844817/

10-10 07:05