What does $(function() {} ); do?
What does $(function() {} ); do?
Sometimes I make a function and call the function later.
Example:
function example { alert('example'); }
example(); // <-- Then call it later
Somehow, some functions cannot be called. I have to call those functions inside:
$(function() { });
What do $(function() {});
and (function() { });
mean, and what's the difference/purpose of these?
回答1
$(function() { ... });
is just jQuery short-hand for
$(document).ready(function() { ... });
What it's designed to do (amongst other things) is ensure that your function is called once all the DOM elements of the page are ready to be used.
However, I don't think that's the problem you're having - can you clarify what you mean by 'Somehow, some functions are cannot be called and I have to call those function inside' ? Maybe post some code to show what's not working as expected ?
Edit: Re-reading your question, it could be that your function is running before the page has finished loaded, and therefore won't execute properly; putting it in $(function) would indeed fix that!
$( document ).ready()
A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ).ready()
will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute. Code included inside $( window ).on( "load", function() { ... })
will run once the entire page (images or iframes), not just the DOM, is ready.
// A $( document ).ready() block. $( document ).ready(function() { console.log( "ready!" ); });
Experienced developers sometimes use the shorthand $()
for $( document ).ready()
. If you are writing code that people who aren't experienced with jQuery may see, it's best to use the long form.
// Shorthand for $( document ).ready() $(function() { console.log( "ready!" ); });
You can also pass a named function to $( document ).ready()
instead of passing an anonymous function.
// Passing a named function instead of an anonymous function. function readyFn( jQuery ) { // Code to run when the document is ready. } $( document ).ready( readyFn ); // or: $( window ).on( "load", readyFn );
实例
$(function () { $jQval.unobtrusive.parse(document); });
What does (function (x,y){...})(a,b); mean in JavaScript?
作者:Chuck Lu GitHub |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2019-01-11 Owin and Startup class
2017-01-11 Stop being a perfectionist
2017-01-11 Medium上的文章