4

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

我将代码移动到函数中以允许我延迟它,因此它不是那么敏感(越来越烦人)

未捕获的 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);
        }
    });
4

1 回答 1

12

看起来您发现使用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;访问。它是私有的,并且仅限于匿名函数的范围。

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

于 2013-02-13T01:15:18.680 回答