4

なぜこれがエラーになるのか誰かに教えてもらえますか?

コードを関数に移動して遅延させ、それほど敏感にならないようにしました(煩わしくなりました)

Uncaught ReferenceError:hideleftnavが定義されていません

Uncaught 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最初の引数として文字列を使用する際に1つの問題が見つかったようです。同じ問題を説明する要約例を次に示します。

(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 に答える