在 jQuery 中设置 init 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17957342/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 20:15:56  来源:igfitidea点击:

Setting up an init function in jQuery

jquery

提问by user2635811

Just a quick question here, I wanted to find out how I could set up these into an init() function then have the function run on document.ready. This code is being used in a separate main.js file. Does it need to be called from the index page?

这里只是一个简单的问题,我想知道如何将这些设置到 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');
    });
});

Any help is appreciated. I'm really trying to wrap my head around this, but I can't seem to find any good tutorials that explain init() well enough for my specific code.

任何帮助表示赞赏。我真的很想解决这个问题,但我似乎找不到任何很好的教程来为我的特定代码解释 init() 。

回答by Antti Haapala

No need for special "calls", include it on the page with <script src="yourfile.js"></script>and just wrap your code as below to make sure that it is executed after the dom is ready (and the elements present).

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

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

});

$( a_function )is short for $(document).ready( a_function ); more about ready handlers in the documentation.

$( a_function )$(document).ready( a_function ); 的缩写 更多关于文档中的就绪处理程序



The reason why $(document).ready(...)/$(...)is needed at all is that jquery selection like $('#main_right_line_one')only sees elements that are present at the execution time in the DOM tree. However, <script>tag contents are usually executed by browsers as soon as they're met; and <script>elements are usually located in <head>. Thus the scripts would often see an incomplete DOM tree. Now, thanks to the design of jQuery, even if $('#main_right_line_one')does not match any elements, there would still be no error; and the clickhandler would be bound to 0 elements.

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

This all can be avoided by wrapping that kind of code in $(function() { ... }), which ensures that whatever code is in it will be executed after the DOM has been fully initialized (or immediately if it already has been initialized).

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



The reason for why there is a shorthand like $(function() {})for $(document).ready(function() {})is that executing code only after the DOM tree has been finished is such a necessary pattern that almost every single page utilizing jQuery would be using.

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

回答by Simon Adcock

In your index page:

在您的索引页面中:

<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>

You're right in that it's good practice to wrap all your code in an object and call that with an init()function. So in you main.js, you could have:

您是对的,将所有代码包装在一个对象中并使用init()函数调用它是一种很好的做法。所以在你main.js,你可以有:

$(document).ready(function() {

    myPage.init();

});

And then below that, you can define your page object like so:

然后在其下方,您可以像这样定义页面对象:

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;

})();