سؤال

I'm newbie to jQuery (I came to JavaScript from PHP).

I grouped multiple jQ functions in seperate files. I have the following questions:

  1. is there any requirement that every jQ function must be inside domready?
  2. What if, 1 of my files already has code that placed inside $(document).ready(function () { });. Can I use Domready more than 1 time?
هل كانت مفيدة؟

المحلول

No, you do not have to have every jquery function within the document ready handler. But if your code references any part of the DOM, you should have it within that context.

You can have any number of functions bound to any event, including document.ready. So feel free to use $(document).ready(function () { }); or even better $(function () {}) all you want.

نصائح أخرى

Not really. Although I do not have enough information comment fully I can say that you only want to execute jquery on "ready" to run jquery on page load. Typically you will want to build jquery based functions and call these at the appropriate times. You can how ever call jquery in different ways, ie: Most importantly I think is that you usually want to make sure the whole DOM structure is loaded.

jQuery.("#id").doStuff(); $("#id).doStuff();

Fairly simple answers to your questions:

  1. No, there is no need to put your jQuery function inside the dom ready, although if you are trying to attach events to dom elements, it is a good place to do it.
  2. You can have multiple document ready functions per page.
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top