最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why do I need to wrap my JQuery code in a function literal? - Stack Overflow

programmeradmin0浏览0评论

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.

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.

However other code can work without being wrapped in a function literal. Example - alert('Hi there')

What is the difference? Why does alert work but the event assignment statement does not?

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.

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.

However other code can work without being wrapped in a function literal. Example - alert('Hi there')

What is the difference? Why does alert work but the event assignment statement does not?

Share Improve this question asked Aug 30, 2012 at 17:29 Kshitiz SharmaKshitiz Sharma 18.7k27 gold badges102 silver badges177 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 7

$(function(){...}); is shorthand for $(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.)

It is not a requirement.

You are putting your code in an event handler that is invoked when the DOM is ready.

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.

If your code doesn't perform DOM selection, then it's not needed. That's why your alert() works, because it doesn't need to fetch any elements.

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 = function() {
    // your code
};

or using 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.

At the most basic level, something of the form (function(){...})() is a function literal that is executed immediately. 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). 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.

发布评论

评论列表(0)

  1. 暂无评论