【问题标题】:jquery ready methodjQuery 就绪方法
【发布时间】:2012-03-11 21:50:56
【问题描述】:

以下 jquery 的 sn-p 表示等到文档准备好。

$(document).ready(function() {  
     // my code
});

还有哪些其他对象可以传递给$() 来代替文档参数。

【问题讨论】:

    标签: jquery dom document-ready


    【解决方案1】:

    根据docs

    .ready() 方法只能在 匹配当前文档的 jQuery 对象上调用

    但我的Fiddle 表明这不是真的!!!

    HTML:

    <div id="gdoron">
        <input value='aaa' />
    </div>​
    

    JavaScript:

    $('#gdoron').ready(function() {
        alert($('#gdoron').html()); // alerts: "<input value='aaa' />"
    });​
    
    alert($('#gdoron').html()); // alerts: "null"
    

    也许文档的意思是处理程序中的this 将是document 对象而不是对应于选择器的元素?(这是真的......)

    触发 readyList 处理程序的代码:

    readyList.fireWith( document, [ jQuery ] );
    

    你为什么不使用document 对象呢?这是唯一始终被定义的 DOM 对象,不像 body 等。


    以下三种语法都是等价的:

    • $(document).ready(handler)
    • $().ready(handler)(不推荐)
    • $(handler)

    【讨论】:

    • 但是如果你 console.log 在你的小提琴代码中你会得到文件作为参考而不是#gdoron 所以你不能使用它例如:$(this).addClass("gdoron")
    • +1 也许这就是文档的意思...?将其添加到我的答案中。谢谢!
    • 在第 435 行(jQuery 1.7.1):readyList.fireWith( document, [ jQuery ] ); 在那里;)(如果你也想添加它?)
    【解决方案2】:

    ready 上的 jQuerys 文档说:

    .ready() 方法只能在匹配当前文档的 jQuery 对象上调用,所以可以省略选择器。

    大多数人都在使用:

    $(function(){});
    

    它更短,更不容易混淆;)

    【讨论】:

      【解决方案3】:

      .ready() 方法只能在匹配当前文档的 jQuery 对象上调用

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-02-15
        • 2011-07-20
        • 1970-01-01
        • 1970-01-01
        • 2011-09-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多