把所有代码放在`$(document).ready`里面安全吗?

6
我正在使用jQuery完成一个小项目,这是我第一次使用它。把所有的UI代码放在$(document).ready()里面安全吗?我的意思是,我正在创建一个表单,在按钮被按下时弹出,然后通过AJAX处理表单。当我将AJAX函数与控制UI的函数分开时,AJAX就不起作用了。但是,当我把它们都放在$(document).ready()里面时,一切都正常工作。以下是我的代码,请忽略我的注释,因为它们只是为了学习目的而存在。
$(document).ready(function(){ //ready for DOM manipulation

/*FORM UI*/
var container_form=$('#container_form'); //container form box
var addButton=$('.addButton'); //"+" add button
container_form.hide(); //initially hides form
$(addButton).click(function(){
$(container_form).toggle('fast');

/*SUBMISSION AJAX*/
$('form.ajax').on('submit',function() { //Make form with class "ajax" a JQuery object

    var that = $(this),                 //"that"-current form, "url"-php file, "type"-post, "data"-empty object for now
        url=that.attr('action'),
        type=that.attr('method'),
        data={};

    that.find('[name]').each(function(index,value){ //search all elements in the form with the attribute "name"
        var that=$(this), //legal attribute
            name=that.attr('name'); //name of the legal attribute
            value=that.val(); //value of text field in legal attribute
            data[name]=value; //data object is filled with text inputs
    });


    $.ajax({
        url: url,   //url of form
        type: type, //type of form
        data: data, //data object generated in previous
        success: function(response){ //reponse handler for php
            if(!response){
                console.log("Error");
            }
            console.log(response);
        }

    });


    return false; //Stops submission from going to external php page. 
});
});
});

4
没问题,它非常安全! - adeneo
谢谢!此外,我看到一些 jQuery 代码中有 js 函数来“加载”某些 UI 元素。这是一种常规/标准做法,还是只局限于那个代码? - Carpetfizz
3个回答

12

通常,任何选择器,如$('form.ajax')。$('#container_form')$('.addButton'),都需要在doc.ready中使用,以确保DOM已准备就绪,然后再尝试从中选择元素,因为如果DOM还没有完成处理,则可能找不到该元素。因此,这基本上适用于您的所有代码。如果您有这样的函数:

//defines a function
function addThem(first,second)
{
   return first + second;
}
你可以在文档加载完成之外声明它,并在文档加载完成后调用它。
$(document).ready(function(){
   $('#someInput').val( 
      addThem( $('#anotherInput').val() , $('#thirdInput').val()  )
   );
});
我对此的看法是,doc ready 是一个事件,因此您应该根据“文档已准备好供您查询事件”做出响应,而不是声明内容。声明函数只是说明该函数的功能,但实际上并不执行任何操作,因此它可以放在 document ready 的外面。如果在 doc.ready 内部声明此函数,这将非常愚蠢,因为它可以随时定义(虽然确实可以把它放在 doc ready 内部,但通常会使事情变得混乱)。即使它正在选择元素,该代码也不会实际运行,直到被调用:
function hideContainer()
{
   //this code never runs until the function is called
   //we're just defining a function that says what will happen when it is called
   return $('#container').hide();
}

$(document).ready(function(){       
    //here we are calling the function after the doc.ready, so the selector should run fine
    hideContainer();
});

请注意,连接到其他事件本身就是一种操作,例如当您订阅点击事件和表单提交事件时。您正在说:“查找类为 .ajax 的表单元素并订阅其提交事件”。在 DOM 处理完成之前,您不应尝试连接到 DOM 元素的事件。如果浏览器正在处理 DOM,则它们可能尚未被“存在”,因此您尝试连接到点击/表单提交事件可能会失败。我说“可能”是因为根据计时/处理延迟的不同,它有时可能有效,有时可能无效。


非常感谢您的回答!我会尽快接受它。也感谢其他的回答,但这个回答阐明了事件函数和普通函数之间的区别。 - Carpetfizz

5

把所有代码放进一个 $(document).ready() 并没有错,同样把它放进多个 $(document).ready() 也没有问题,这样你可以把重复的功能分成不同的JS文件。

例如,我在一个包含在所有网页中的脚本中使用 $(document).ready() 来设置 UI 元素、防止点击劫持等。同时,每个页面都有自己的 $(document).ready(),用于设置特定页面的用户交互。


2

完全没有问题。如果您发现需要将代码抽象为多个函数或多个文件,则可以这样做,但是将所有内容放在$(document).ready()中也没有问题。


1
注意:$(document).ready(function(){...}); 还可以简写为 $(function(){...});。http://learn.jquery.com/using-jquery-core/document-ready/ - showdev
@showdev 我认为一些人更喜欢使用$(document).ready(包括我自己),因为这样更易读。我认为这只是一个“品味”的问题。(我在js和jquery方面还很新,所以我不知道是否存在任何性能问题) - paraJdox1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接