13

ここで簡単な質問ですが、これらを init() 関数に設定し、その関数を document.ready で実行する方法を知りたいと思いました。このコードは、別の main.js ファイルで使用されています。インデックスページから呼び出す必要がありますか?

$('#main_right_line_one').click(function(){
    $('#main_regular_layover, #main_deep_layover').fadeOut('slow', function(){
        $('#main_light_layover').fadeIn('slow');
    });
});

$('#main_right_line_two').click(function(){    
    $('#main_light_layover, #main_deep_layover').fadeOut('slow', function(){
        $('#main_regular_layover').fadeIn('slow');
    });
});

$('#main_right_line_three').click(function(){
    $('#main_light_layover, #main_regular_layover').fadeOut('slow', function(){
        $('#main_deep_layover').fadeIn('slow');
    });
});

どんな助けでも大歓迎です。私は本当にこれに頭を悩ませようとしていますが、 init() を私の特定のコードに十分に説明する良いチュートリアルを見つけることができないようです。

4

2 に答える 2

22

インデックス ページで:

<html>
<head>
    <title>Your title</title>
</head>
<body>

    <!-- Your HTML here -->

    <script src="http://code.jquery.com/jquery-2.0.0.js"></script>
    <script src="main.js"></script>
</body>

すべてのコードをオブジェクトにラップし、それを関数で呼び出すことをお勧めしますinit()。したがって、あなたmain.jsには次のものがあります。

$(document).ready(function() {

    myPage.init();

});

その下で、次のようにページ オブジェクトを定義できます。

var myPage = (function() {

    var that = {};

    that.init = function () {

        $('#main_right_line_one').click(function(){
            $('#main_regular_layover, #main_deep_layover').fadeOut('slow', function(){
                $('#main_light_layover').fadeIn('slow');
            });
        });

        $('#main_right_line_two').click(function(){    
            $('#main_light_layover, #main_deep_layover').fadeOut('slow', function(){
                $('#main_regular_layover').fadeIn('slow');
            });
        });

        $('#main_right_line_three').click(function(){
            $('#main_light_layover, #main_regular_layover').fadeOut('slow', function(){
                $('#main_deep_layover').fadeIn('slow');
            });
        });

    }

    return that;

})();
于 2013-07-30T21:09:30.527 に答える