jQuery $( function() {} ) and $(document).ready the same?
jQuery $( function() {} ) and $(document).ready the same?
要在字段上有一个工作日期选择器,我必须把这个脚本放在我的元素中
$( function() {
$( "#date_datepicker" ).datepicker( { dateFormat: "yy-mm-dd" } );
});
删除$( function() {
会使日期选取器不起作用。
那么这是否意味着$( function() {
和$(document).ready
一样?
我正在尝试优化我的 JavaScript 代码,所以知道这可能会有所帮助。
请参阅下面的摘录 http://api.jquery.com/ready/
以下三种语法都是等效的:
$(document).ready(handler)
$().ready(handler)
(不推荐这样做)$(handler)
.ready() 方法通常与匿名函数一起使用:
$(document).ready(function() {
// Handler for .ready() called.
});
这相当于调用:
$(function() {
// Handler for .ready() called.
});
可以在这里阅读
是的,它是同一事物的速记版本。$
函数在将函数作为参数传递时调用$(document).ready
函数。
如果您尝试在速度方面进行优化 - 两者的性能几乎相同,但是如果执行多次,较长的$(document).ready(handler)
将速度最小。
如果您尝试优化文件大小 - 请使用缩小器。
IMO 你能做的最好的事情就是在可读性和简单性方面进行"优化"。这使得代码更容易理解和维护。有一些工具可以采用未优化的版本并为您压缩和优化(查看Google的闭包编译器)。
是的,$( function() {
和$(document).ready
是相同的。
$( function() {
用作速记语法,但$(document).ready
使代码更具可读性。
这是一种非常安全的方法,可以在 ready 上运行代码
jQuery(function($, undefined){
// code to run onready
});
虽然我个人更喜欢这样做:
(function($){ // create scope and pass specific aliased variables
$(function($, undefined){ // attach callback to run onready
// code to run onready
});
})(jQuery);
通过这种方式,您可以制作自己的功能包,而不必担心破坏其他人的代码或您的代码被松散的变量定义破坏。例如,您还可以调用传递的变量以及所需的任何名称,并具有在就绪时不运行的代码。
(function($){ // create scope and pass specific aliased variables
$(document).on('click', 'a[href]', function(){
// code to run when a link is clicked
});
$(window).on('load',function(){
// code to run onload
});
$(function($, undefined){ // attach callback to run onready
// code to run onready
});
})(jQuery);
请注意,这些是相同的
$(document).bind('ready', function(){});
$(document).on('ready', function(){});
$(document).ready(function(){});
$(function(){});
并且该文档没有加载事件
$(document).on('load', function(){}); // will not work
请注意,您还可以找到如下脚本:
jQuery(document).ready(function(){
这里的 $-符号被 jQuery 替换,以避免与其他库的冲突
http://docs.jquery.com/Using_jQuery_with_Other_Libraries
你正在使用jQuerymobile吗? 如果是这样,而不是使用文档准备使用
$('#pageId').live('pageinit',function(){});
- 正在寻找比$(document).ready慢的$(window).load的替代方案
- jQuery document.ready not working
- Intercept the cellSubmit jqGrid
- CSS中的游标属性似乎不适用于USB On The Go
- jQuery加载的async和ready函数不工作
- 如何通过documents.ready函数中的javascript自动按键(ctrl+shift+i)
- jQuery document.ready停止代码
- 停止对document.ready函数的重定向/刷新
- $(document).ready和jQuery(function($)不工作;jQuery已定义,但脚本尚未定义;t进
- ready函数在每个页面中触发
- Appending the innerhtml of <th>
- 函数从$(document).ready外部调用在$(document).ready中定义的函数
- jquery in the middle of html
- Can't get the tail to wag (animate) in three.js?
- 如果没有document.ready(),我怎么能拥有多个javascript函数呢
- ASPX Jquery 1.11 $(Document).ready(function() {} was skipped
- 重载像$(document).ready这样的函数是错误的
- jQuery $( function() {} ) and $(document).ready the same?
- Document.ready for the target page not getting invoked using
- wkhtmltopdf and the jQuery.ready() function