5

我正在将 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

3 回答 3

11

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

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

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

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

我的想法是,文档准备好是一个事件,所以你应该做一些事情来响应“文档现在准备好让你查询事件”,而不是声明事情。声明函数只是说明该函数做了什么,但实际上并没有做任何事情,所以它可以在文档之外准备好。在 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,它们可能还不“存在”,因此您尝试连接到单击/表单提交事件可能会失败。我说可能是因为取决于时间/处理滞后,它有时可能有效,有时无效。

于 2013-09-05T23:42:03.427 回答
4

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

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

于 2013-09-05T23:40:05.193 回答
1

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

于 2013-09-05T23:34:22.993 回答