简体   繁体   English

为什么我需要将JQuery代码包装在函数文字中?

[英]Why do I need to wrap my JQuery code in a function literal?

I have following code that works - 我有以下代码可行 -

$(function(){
    $('#testbutton').click(function(){
        var checkedValue = $('[name="someRadioGroup"]:radio:checked').val();
        $('#result').html('The radio element with value <tt>' + checkedValue + '</tt> is checked');
    });
});

I understand that $('#testbutton') fetches the HTML element with id testbutton and assigns an event handler to it. 我知道$('#testbutton')使用id testbutton获取HTML元素并为其分配一个事件处理程序。

But I don't understand why I need to put that code inside a function literal? 但我不明白为什么我需要将该代码放在函数文字中?

If I remove the $(function(){ (and the corresponding }); ) it does not work. 如果我删除$(function(){ (和相应的}); )它不起作用。

However other code can work without being wrapped in a function literal. 但是,其他代码可以在不包含在函数文字中的情况下工作。 Example - alert('Hi there') 示例 - alert('Hi there')

What is the difference? 有什么区别? Why does alert work but the event assignment statement does not? 为什么警报工作但事件赋值语句没有?

$(function(){...}); is shorthand for $(document).ready(function(){...}); $(document).ready(function(){...});简写$(document).ready(function(){...}); . The purpose of it is to not run your code until the elements that you intend to work with exist in the DOM (which generally is after the document is ready.) 它的目的是在您打算使用的元素存在于DOM中之前不运行代码(通常在文档准备好之后)。

It is not a requirement. 这不是必需的。

You are putting your code in an event handler that is invoked when the DOM is ready. 您将代码放在DOM准备就绪时调用的事件处理程序中。

If you don't put your code in a DOM ready handler, and if your code performs DOM selection, you need to find some other way to to make sure the DOM is ready before it runs. 如果您没有将代码放在DOM就绪处理程序中,并且您的代码执行DOM选择,则需要找到一些其他方法来确保DOM在运行之前就绪。

If your code doesn't perform DOM selection, then it's not needed. 如果您的代码没有执行DOM选择,则不需要它。 That's why your alert() works, because it doesn't need to fetch any elements. 这就是你的alert()有效的原因,因为它不需要获取任何元素。

An alternative is this. 另一种选择就是这样。

<body>
   <button id="testbutton">click</button>
   <div id="result"></div>

   <script type="text/javascript" src="/your/script.js"></script>
</body>

This places your code below all the elements on the page, so they are certain to be available when your code runs. 这会将代码放在页面上的所有元素下面,因此在代码运行时它们肯定可用。

Another alternative is to use a window.onload handler. 另一种方法是使用window.onload处理程序。

window.onload = function() {
    // your code
};

or using jQuery. 或者使用jQuery。

$(window).on("load", function() {
    // your code
});

This is similar to the DOM ready handler, except that it waits for all resource, like images, to be loaded. 这类似于DOM就绪处理程序,除了它等待加载所有资源(如图像)。

At the most basic level, something of the form (function(){...})() is a function literal that is executed immediately. 在最基本的层面上,某些形式(function(){...})()是一个立即执行的函数文字。 What this means is that you have defined a function and you are calling it immediately. 这意味着您已经定义了一个函数,并且您正在立即调用它。

This form is useful for information hiding and encapsulation since anything you define inside that function remains local to that function and inaccessible from the outside world (unless you specifically expose it - usually via a returned object literal). 此表单对于信息隐藏和封装非常有用,因为您在该函数内定义的任何内容都保留在该函数的本地,并且无法从外部世界访问(除非您专门公开它 - 通常通过返回的对象文字)。

A variation of this basic form is what you see in jQuery plugins (or in this module pattern in general). 这个基本形式的变体就是你在jQuery插件中看到的(或者通常在这个模块模式中)。 Since you are defining a function literal, it doesn't have access to anything from the outside world unless you explicitly pass in the information. 由于您要定义函数文字,除非您明确传入信息,否则它无法访问来自外部世界的任何内容。 Hence: 因此:

(function($) {
  ...
})(jQuery);

Which means you're passing in a reference to the actual jQuery object, but it's known as $ within the scope of the function literal. 这意味着你传递了对实际jQuery对象的引用,但它在函数文字的范围内被称为$。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么在传递/公开EventEmitter的on函数时需要包装它? - Why do I need to wrap my EventEmitter's on function when passing/exposing it? jQuery / JavaScript,为什么需要将变量包装在$()中才能使用它们? - jQuery / JavaScript, why do I need to wrap variables in $() to use them? 为什么我需要将代码包装在立即调用的函数表达式中? - Why I need to wrap the code in immediately invoked function expression? (javascript)为什么我需要为事件处理程序使用wrap函数? - (javascript) why do i need to use a wrap function for event handlers? 为什么将JavaScript封装在“((function($){…JavaScript code ..})(jQuery);”)中? - Why wrap JavaScript in this “(function($){ … JavaScript code ..})(jQuery);”? 为什么我需要将 setState 回调包装在匿名箭头函数中才能在状态更改后运行? - Why do I need to wrap setState callback in an anonymous arrow function for it to run after state change? 我需要帮助使JQuery Function slideDown在我的代码中工作 - I need help getting the JQuery Function slideDown to work in my code 我需要重复多少 javascript jquery 代码? - How much of my javascript jquery code do I need to repeat? 为什么我必须在脚本代码之外添加$(function()…)?Javascript,骨干网,Jquery - Why do I have to add $(function()…) outer of my script code?Javascript, backbone, Jquery 为什么我需要在setTimeout中使用匿名函数才能使此代码生效? - Why do I need to have anonymous function in the setTimeout for this code to work?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM