将所有代码放在`$(document).ready`中是否安全?

Car*_*izz 4 javascript ajax jquery

我正在使用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. 
});
});
});
Run Code Online (Sandbox Code Playgroud)

Aar*_*nLS 9

通常,任何选择器(例如$('form.ajax').,$('#container_form'))都$('.addButton') 需要在doc.ready中,以确保在您尝试从中选择元素之前已准备好DOM,因为如果DOM尚未完成处理,它可能无法找到该元素.所以这几乎适用于你的所有代码.如果你有这样的功能:

//defines a function
function addThem(first,second)
{
   return first + second;
}
Run Code Online (Sandbox Code Playgroud)

您可以在doc准备就绪之外声明它,并在doc ready中调用它.

$(document).ready(function(){
   $('#someInput').val( 
      addThem( $('#anotherInput').val() , $('#thirdInput').val()  )
   );
});
Run Code Online (Sandbox Code Playgroud)

我想到的方式是,doc就绪是一个事件,所以你应该做的事情是响应"文档现在已经准备好让你查询事件",而不是声明事情.声明函数只是表示该函数的作用,但实际上并没有做任何事情,所以它可以在文档之外准备就绪.在doc.ready中声明这个函数是非常愚蠢的,因为它可以在任何时候定义(虽然它确实可以把它放在doc中,但它通常会使事情变得混乱).即使它正在选择一个元素,该代码在被调用之前实际上并未运行:

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();
});
Run Code Online (Sandbox Code Playgroud)

请注意,连接到其他事件的行为本身就是一个操作,例如当您订阅click事件和表单提交事件时.你说,"找到带有.ajax类的表单元素,并订阅它的提交事件".在DOM完成处理之前,您不希望尝试连接DOM元素的事件.就浏览器而言,如果它处于处理DOM的过程中,它们可能不会"存在",因此您尝试连接点击/表单提交事件可能会失败.我说可能是因为取决于时间/处理延迟,它有时可能有效,有时不工作.


sus*_*n97 5

将所有代码放入一个中不仅没有任何问题$(document).ready(),而且将其放入多个 $(document).ready()函数中也没有任何问题,这样您就可以将重复的功能分离到单独的 JS 文件中。

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