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

时间:2013-09-05 23:29:36

标签: javascript jquery ajax

我正在使用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. 
});
});
});

3 个答案:

答案 0 :(得分:9)

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

//defines a function
function addThem(first,second)
{
   return first + second;
}

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

$(document).ready(function(){
   $('#someInput').val( 
      addThem( $('#anotherInput').val() , $('#thirdInput').val()  )
   );
});

我想到的方式是,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();
});

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

答案 1 :(得分:4)

将所有代码放入一个$(document).ready()不仅没有错,而且将它放入multiple $(document).ready()函数也没有错您可以将重复的功能分成单独的JS文件。

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

答案 2 :(得分:1)

绝对没问题。如果您发现自己需要将代码抽象为多个函数或多个文件,那么无论如何,将所有内容都放在$(document).ready()中并没有错。