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

38

不需要特殊的“调用”,将其包含在页面中,<script src="yourfile.js"></script>并按如下方式包装您的代码,以确保它在 dom 准备好(并且元素存在)之后执行。

$(function () {
   // your code goes here

});

$( a_function )$(document).ready( a_function );的缩写 有关文档中准备好的处理程序的更多信息。


$(document).ready(...)完全需要/的原因$(...)是 jquery selection like$('#main_right_line_one')只看到 DOM 树中执行时存在的元素。但是,<script>标签内容通常在浏览器遇到后立即执行;元素<script>通常位于<head>. 因此,脚本经常会看到不完整的 DOM 树。现在,感谢jQuery的设计,即使$('#main_right_line_one')不匹配任何元素,仍然不会出错;并且click处理程序将绑定到 0 个元素。

这一切都可以通过将这种代码包装在 中来避免$(function() { ... }),这确保了其中的任何代码都将在 DOM 完全初始化后执行(或者如果它已经初始化,则立即执行)。


之所以有类似$(function() {})for的简写,$(document).ready(function() {})是因为只有在 DOM 树完成后才执行代码是一种非常必要的模式,几乎每个使用 jQuery 的页面都会使用。

于 2013-07-30T21:04:03.930 回答
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 回答