admin管理员组文章数量:1277900
Are these both the same thing, i.e. ways of saying document ready:
$(function() {
//
});
and
$(function($) {
//
})(jQuery);
or is there a difference between the two, if so then when should I use which?
Are these both the same thing, i.e. ways of saying document ready:
$(function() {
//
});
and
$(function($) {
//
})(jQuery);
or is there a difference between the two, if so then when should I use which?
Share Improve this question asked Aug 6, 2011 at 22:07 SergioSergio 1,0771 gold badge8 silver badges5 bronze badges 4- 3 The last one is used when working with various JS libraries together. – Mārtiņš Briedis Commented Aug 6, 2011 at 22:09
- You might want to see stackoverflow./questions/1388043/… – coreyward Commented Aug 6, 2011 at 22:10
- @Briedis so would using the 2nd in a plugin minimize the chances of conflict with other libraries? – Sergio Commented Aug 6, 2011 at 22:20
- Ofcourse, because you pass the jQuery object as a local variable "$". Conflicts exist, if other libraries want to use the "$" global variable too. – Mārtiņš Briedis Commented Aug 6, 2011 at 22:39
3 Answers
Reset to default 9The first one is a shortcut for .ready()
.
The second one is simply invalid as you're trying to call a non-callable object.
You probably meant this:
// v--------no $ at the beginning
(function( $ ) {
// simply a new lexical environment with a
// local $ parameter pointing to jQuery
})(jQuery);
...though it has nothing to do with DOM ready.
There is a variation on your first example that bines the two:
jQuery(function( $ ) {
// DOM ready, and creates a local $ parameter pointing to jQuery
});
They both are not same.
First code block is used to execute the function on document ready where as second code block is used when we want to execute the code block immediately without waiting for rest of the code to be loaded. But there is some error in your second part of the code. It should be as below.
(function($) {
//
})(jQuery);
This one is incorrect:
$(function($) {
//
})(jQuery);
You're passing a function to $(...)
, then calling the result. However, the result of $(...)
is a jQuery object, which is not a function. You might see it better this way:
$(
function($) {
//
}
)
(jQuery);
Generally, there are three versions of document.ready
, which are all equal to each other:
$(function() {...});
$(document).ready(function() {...});
$().ready(function() {...});
本文标签: javascriptDifferent ways of saying document ready in jQueryStack Overflow
版权声明:本文标题:javascript - Different ways of saying document ready in jQuery? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741268499a2368895.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论