settimeout给出Uncaught ReferenceError:函数未定义

Kel*_*sen 3 javascript jquery settimeout

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

我将代码移动到函数中以允许我延迟它,因此它不那么敏感(令人讨厌)

未捕获的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);
        }
    });
Run Code Online (Sandbox Code Playgroud)

Ble*_*der 11

看起来你发现使用setTimeout字符串作为第一个参数有一个问题.这是一个简洁的例子,说明了同样的问题:

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

    setTimeout('test()', 500);  // ReferenceError: test is not defined
    setTimeout(test, 500);      // "test"
    setTimeout(function() {     // "test"
        test();
    }), 500);
})();
Run Code Online (Sandbox Code Playgroud)

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

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

引用该函数只是test避免了这个问题,因为你直接指向函数而不使用eval.