Jquery 3.2.0 is out!

Минус: вы контролируете не всё

Если вам нужен мак­си­маль­ный кон­троль за всем, что про­ис­хо­дит на сай­те, то луч­ше исполь­зо­вать чистый JavaScript. В этом слу­чае вы пол­но­стью уве­ре­ны в том, как ведёт себя стра­ни­ца, и не зави­си­те от сто­рон­не­го кода.


Если исполь­зу­е­те ред­кий пла­гин, есть риск, что он может не рабо­тать настоль­ко надёж­но, как вам нуж­но. К тому же, не все сто­рон­ние пла­ги­ны так же хоро­шо опти­ми­зи­ро­ва­ны, как сам jQuery: в ито­ге у вас ради какого-то одно­го эффек­та или бло­ка на стра­ни­це появит­ся огром­ная биб­лио­те­ка, кото­рая будет всё страш­но замед­лять.

Assignment

Assignment works a little differently in jq than in most programming languages. jq doesn’t distinguish between references to and copies of something — two objects or arrays are either equal or not equal, without any further notion of being «the same object» or «not the same object».

If an object has two fields which are arrays, and , and you append something to , then will not get bigger. Even if you’ve just set . If you’re used to programming in languages like Python, Java, Ruby, Javascript, etc. then you can think of it as though jq does a full deep copy of every object before it does the assignment (for performance, it doesn’t actually do that, but that’s the general idea).

Array

Arrays in JavaScript are mutable lists with a few built-in methods. You can define arrays using the array literal:

1 2

The type of an array is «object»:

1 2

Reading and writing elements to an array uses the array-notation:

1 2

Iteration

An array has a length property that is useful for iteration:

1 2 3

When performance is critical, reading the length property only once can help to speed things up. This should be used only when a performance bottleneck was discovered:

1 2 3

Another variation defines a variable that is filled for each iteration, removing the array-notation from the loop-body. It does not work when the array contains 0 or empty strings!

1 2 3

jQuery provides a generic each function to iterate over element of arrays, as well as properties of objects:

1 2 3 4

The drawback is that the callback is called in the context of each value and you therefore lose the context of your own object if applicable. More on this below at Functions.

The length property can also be used to add elements to the end of an array. That is equivalent to using the push-method:

1 2 3 4

You’ll see both variations a lot when looking through JavaScript library code.

Other built-in methods are reverse, join, shift, unshift, pop, slice, splice and sort:

1 2 3 4 5 6 7 8

Note: .unshift() method does not return a length property in Internet Explorer.

An array, no matter if it has elements or not, never defaults to false:

1 2

Array<Type> Notation

In the jQuery API you’ll often find the notation of Array<Type>:

dragPrevention    Array<String>

This indicates that the method doesn’t only expect an array as the argument, but also specifies the expected type. The notation is borrowed from Java 5’s generics notation (or C++ templates).

jQuery Exam — Get Your Diploma!

W3Schools’ Online Certification

The perfect solution for professionals who need to balance work, family, and career building.

More than 25 000 certificates already issued!

The HTML Certificate documents your knowledge of HTML.

The CSS Certificate documents your knowledge of advanced CSS.

The JavaScript Certificate documents your knowledge of JavaScript and HTML DOM.

The Python Certificate documents your knowledge of Python.

The jQuery Certificate documents your knowledge of jQuery.

The SQL Certificate documents your knowledge of SQL.

The PHP Certificate documents your knowledge of PHP and MySQL.

The XML Certificate documents your knowledge of XML, XML DOM and XSLT.

The Bootstrap Certificate documents your knowledge of the Bootstrap framework.

jQuery Migrate — All Versions

  • jQuery Migrate 3.3.1 — uncompressed, minified
  • jQuery Migrate 3.3.0 — uncompressed, minified
  • jQuery Migrate 3.2.0 — uncompressed, minified
  • jQuery Migrate 3.1.0 — uncompressed, minified
  • jQuery Migrate 3.0.1 — uncompressed, minified
  • jQuery Migrate 3.0.0 — uncompressed, minified
  • jQuery Migrate 1.4.1 — uncompressed, minified
  • jQuery Migrate 1.4.0 — uncompressed, minified
  • jQuery Migrate 1.3.0 — uncompressed, minified
  • jQuery Migrate 1.2.1 — uncompressed, minified
  • jQuery Migrate 1.2.0 — uncompressed, minified
  • jQuery Migrate 1.1.1 — uncompressed, minified
  • jQuery Migrate 1.1.0 — uncompressed, minified
  • jQuery Migrate 1.0.0 — uncompressed, minified

Минус: много всего

Под­клю­чать целую биб­лио­те­ку ради одно­го эффек­та — не самая луч­шая идея. Ино­гда про­ще потра­тить лиш­них пять минут и сде­лать то же самое на JavaScript, чем тащить в про­ект лиш­них 64 кило­бай­та кода.

Напри­мер, что­бы одно­крат­но вызвать обра­бот­чик собы­тия, мож­но под­клю­чить jQuery и напи­сать так:

$elem.one(«click», someFunc);

А мож­но ниче­го не под­клю­чать и исполь­зо­вать про­стой JavaScript, кото­рый уже научил­ся делать то же самое через тре­тий, необя­за­тель­ный, пара­метр в addEventListener:

elem.addEventListener(‘click’, someFunc, { once: true, });

The event handler and its environment

The argument is a function (or the value , see below), and is required unless you pass an object for the argument. You can provide an anonymous handler function at the point of the call, as the examples have done above, or declare a named function and pass its name:

1 2 3 4

When the browser triggers an event or other JavaScript calls jQuery’s method, jQuery passes the handler an object it can use to analyze and change the status of the event. This object is a normalized subset of data provided by the browser; the browser’s unmodified native event object is available in . For example, contains the event name (e.g., «resize») and indicates the deepest (innermost) element where the event occurred.

By default, most events bubble up from the original event target to the element. At each element along the way, jQuery calls any matching event handlers that have been attached. A handler can prevent the event from bubbling further up the document tree (and thus prevent handlers on those elements from running) by calling . Any other handlers attached on the current element will run however. To prevent that, call . (Event handlers bound to an element are called in the same order that they were bound.)


Similarly, a handler can call to cancel any default action that the browser may have for this event; for example, the default action on a event is to follow the link. Not all browser events have default actions, and not all default actions can be canceled. See the for details.

Returning from an event handler will automatically call and . A value can also be passed for the as a shorthand for . So, attaches an event handler to all links with class «disabled» that prevents them from being followed when they are clicked and also stops the event from bubbling.

When jQuery calls a handler, the keyword is a reference to the element where the event is being delivered; for directly bound events this is the element where the event was attached and for delegated events this is an element matching . (Note that may not be equal to if the event has bubbled from a descendant element.) To create a jQuery object from the element so that it can be used with jQuery methods, use .

htmlString

A string is designated htmlString in jQuery documentation when it is used to represent one or more DOM elements, typically to be created and inserted in the document. When passed as an argument of the function, the string is identified as HTML if it starts with ) and is parsed as such until the final character. Prior to jQuery 1.9, a string was considered to be HTML if it contained anywhere within the string.

When a string as passed as an argument to a manipulation method such as , it is always considered to be HTML since jQuery’s other common interpretation of a string (CSS selectors) does not apply in those contexts.

For explicit parsing of a string to HTML, the method is available as of jQuery 1.8.

1 2 3 4 5 6 7 8 9 10 11 12 13 14

jQuery Exercises

jQuery Examples

Learn by examples! At W3Schools you will find a lot of jQuery examples to edit and test yourself.

See All jQuery Examples

Test your jQuery skills at W3Schools!

Start jQuery Quiz!

jQuery References

At W3Schools you will find a complete reference of all jQuery selectors, methods, properties and events.

jQuery Reference

W3Schools’ Online Certification

The perfect solution for professionals who need to balance work, family, and career building.

More than 25 000 certificates already issued!

The HTML Certificate documents your knowledge of HTML.

The CSS Certificate documents your knowledge of advanced CSS.

The JavaScript Certificate documents your knowledge of JavaScript and HTML DOM.

The Python Certificate documents your knowledge of Python.

The jQuery Certificate documents your knowledge of jQuery.

The SQL Certificate documents your knowledge of SQL.

The PHP Certificate documents your knowledge of PHP and MySQL.

The XML Certificate documents your knowledge of XML, XML DOM and XSLT.

The Bootstrap Certificate documents your knowledge of the Bootstrap framework.

Дополнительные примечания

Система событий jQuery требует, чтобы элементы DOM позволяли присоединять данные через свойство к элементам так, чтобы события могли быть отслежены и доставлены. Однако элементам , и невозможно прикреплять данные, и, следовательно, невозможно связывать события с ними через jQuery.

События и , по стандарту W3C, не являются всплывающими, но jQuery определяет кросс-браузерные всплывающие события и . Когда используются и , для назначения делегированных обработчиков событий, jQuery изменяет их имена и передает как и соответственно. Для согласованности и прозрачности, используйте всплывающие типы событий.

Во всех браузерах события , и (например, для элемента ) не всплывающие. В Internet Explorer 8 и ниже, события и не всплывающие. Эти события не используются для делегирования, но они могут быть использованы, когда обработчик событий непосредственно связан с элементом , генерирующим событие.

Событие в объекте использует нестандартные аргументы и конвенции возвращаемого значения — по этому событие не поддерживается в jQuery. Вместо этого назначьте свою функцию обработчика непосредственно к свойству .

link Using jQuery with a CDN

CDNs can offer a performance benefit by hosting jQuery on servers spread across the globe. This also offers an advantage that if the visitor to your webpage has already downloaded a copy of jQuery from the same CDN, it won’t have to be re-downloaded.

jQuery’s CDN provided by StackPath

The jQuery CDN supports Subresource Integrity (SRI) which allows the browser to verify that the files being delivered have not been modified. This specification is currently being implemented by browsers. Adding the new integrity attribute will ensure your application gains this security improvement as browsers support it.

To use the jQuery CDN, just reference the file in the script tag directly from the jQuery CDN domain. You can get the complete script tag, including Subresource Integrity attribute, by visiting https://code.jquery.com and clicking on the version of the file that you want to use. Copy and paste that tag into your HTML file.

Starting with jQuery 1.9, are available on the jQuery CDN. However, as of version 1.10.0/2.1.0 the compressed jQuery no longer includes the sourcemap comment in CDN copies because it requires the uncompressed file and sourcemap file to be placed at the same location as the compressed file. If you are maintaining local copies and can control the locations all three files, you can add the sourcemap comment to the compressed file for easier debugging.

To see all available files and versions, visit https://code.jquery.com

Other CDNs

The following CDNs also host compressed and uncompressed versions of jQuery releases. Starting with jQuery 1.9 they may also host ; check the site’s documentation.

Note that there may be delays between a jQuery release and its availability there. Please be patient, they receive the files at the same time the blog post is made public. Beta and release candidates are not hosted by these CDNs.

  • CDNJS CDN
  • jsDelivr CDN

Плюс: плагины на любой случай

Что бы вы ни хоте­ли сде­лать на веб-странице, ско­рее все­го, для это­го уже есть гото­вые пла­ги­ны на jQuery. Фор­мы под­пис­ки, всплы­ва­ю­щая рекла­ма, захват теле­фон­но­го номе­ра — всё это уже есть и доступ­но за пару команд.

Несколь­ко при­ме­ров:

Scrollpane — кроссбра­у­зер­ный скрол­бар любо­го эле­мен­та на стра­ни­це;


jReject — про­ве­ря­ет, не уста­рел ли исполь­зу­е­мый бра­у­зер;

GridScrolling — нави­га­ция по сай­ту с помо­щью кла­виш;

FlickerPlate — пла­гин для слай­де­ров с под­держ­кой сен­сор­ных экра­нов;

Animsition — созда­ние ани­ми­ро­ван­ной загруз­ки стра­ниц на сай­те;

SlideBars — созда­ние адап­тив­но­го меню на сай­те

и ещё тыся­чи гото­вых пла­ги­нов.

link About the Code

jQuery is provided under the MIT license.

The code is hosted and developed in the jQuery GitHub repository. If you’ve spotted some areas of code that could be improved, please feel free to discuss it on the Developing jQuery Core Forum. If you’d like to participate in developing jQuery, peruse our contributor site for more information.

To find and download plugins developed by jQuery contributors, please visit the Plugins site. Plugin authors are responsible for maintenance of their plugins. Feedback on plugins should be directed to the plugin author, not the jQuery team.

Build from Git

Note: To just use the latest work-in-progress version of jQuery, please try the jQuery Pre-Release Build described above.

All source code is kept under Git revision control, which you can browse online. The repository’s README has more information on building and testing your own jQuery, as well as instructions on creating a custom build that excludes some APIs to reduce file size.

If you have access to Git, you can connect to the repository here:

1

You can also check out and build a specific version of jQuery from GitHub:

1 2

The README file for a specific version will have instructions for building that version, as the process has changed over time.

String

A string in JavaScript is an immutable primitive value that contains none, one or many characters.

1 2

The type of a string is «string».

1

Quoting

A string can be defined using single or double quotes. You can nest single quotes inside of double quotes, and the other way around. To mix double quotes with double quotes (or single with single), the nested ones have to be escaped with a backslash.

1 2 3

Built-in Methods

A string in JavaScript has some built-in methods to manipulate the string, though the result is always a new string — or something else, eg. split returns an .

1 2 3 4 5

All strings have a length property.

1 2

jQuery UI 1.10

uncompressedminified

Themes

black-tieblitzercupertinodark-hivedot-luveggplantexcite-bikeflickhot-sneakshumanityle-frogmint-chocovercastpepper-grinderredmondsmoothnesssouth-streetstartsunnyswanky-pursetrontasticui-darknessui-lightnessvader

Previous Releases

  • jQuery UI 1.10.3 — uncompressed, minified, theme
  • jQuery UI 1.10.2 — uncompressed, minified, theme
  • jQuery UI 1.10.1 — uncompressed, minified, theme
  • jQuery UI 1.10.0 — uncompressed, minified, theme
  • jQuery UI 1.10.0-rc.1 — uncompressed, minified, theme
  • jQuery UI 1.10.0-beta.1 — uncompressed, minified, theme

Минус: нет понимания технологии

Чрез­мер­ное увле­че­ние jQuery может при­ве­сти к тому, что про­грам­мист про­сто не будет пони­мать, как рабо­та­ют меха­низ­мы у него на стра­ни­це и не смо­жет их испра­вить, если что-то пой­дёт не так.

Напри­мер, про­грам­мист при­кру­тил на стра­ни­цу какой-то эффект на базе jQuery. Потом еще один, и они нача­ли кон­флик­то­вать. Если про­грам­мист не может разо­брать­ся в устрой­стве этих биб­лио­тек, он не смо­жет раз­ре­шить кон­фликт — а для это­го нуж­но пони­мать чистый javaScript и уметь отла­жи­вать код.

Полу­ча­ет­ся, что знать jQuery всё-таки полез­но, но нуж­но пони­мать, когда без него мож­но обой­тись.

Ско­ро возь­мем эту биб­лио­те­ку за осно­ву и сде­ла­ем какой-нибудь полез­ный про­ект. Под­пи­сы­вай­тесь, мы напи­шем, когда что-нибудь такое вый­дет.

Плюс: кроссбраузерность

Мно­гие поль­зо­ва­те­ли исполь­зу­ют ста­рые бра­у­зе­ры, напри­мер Internet Explorer 11. Они это дела­ют не пото­му, что не зна­ют, как обно­вить­ся, а пото­му что на рабо­те админ запре­тил уста­нов­ку любо­го соф­та; или в госу­че­ре­жде­ни­ях дав­но не обнов­ля­ли ком­пью­те­ры.

Тут и спа­са­ет jQuery: раз­ра­бот­чи­ки сами преду­смот­ре­ли под­держ­ку ста­рых бра­у­зе­ров. Напри­мер, вот как может выгля­деть про­вер­ка на вер­сии Intertet Explorer:

И такие услов­ные бло­ки есть для всех ста­рых вер­сий IE.

Если всё настоль­ко кру­то, как здесь напи­са­но, то все долж­ны уже были дав­но перей­ти на jQuery и забыть про JavaScript, но это­го не про­ис­хо­дит. Более того, у jQuery есть свои суще­ствен­ные мину­сы и огра­ни­че­ния.

Assignment

Assignment works a little differently in jq than in most programming languages. jq doesn’t distinguish between references to and copies of something — two objects or arrays are either equal or not equal, without any further notion of being «the same object» or «not the same object».

If an object has two fields which are arrays, and , and you append something to , then will not get bigger. Even if you’ve just set . If you’re used to programming in languages like Python, Java, Ruby, Javascript, etc. then you can think of it as though jq does a full deep copy of every object before it does the assignment (for performance, it doesn’t actually do that, but that’s the general idea).

jQuery Core — All 1.x Versions

  • jQuery Core 1.12.4 — uncompressed, minified
  • jQuery Core 1.12.3 — uncompressed, minified
  • jQuery Core 1.12.2 — uncompressed, minified
  • jQuery Core 1.12.1 — uncompressed, minified
  • jQuery Core 1.12.0 — uncompressed, minified
  • jQuery Core 1.11.3 — uncompressed, minified
  • jQuery Core 1.11.2 — uncompressed, minified
  • jQuery Core 1.11.1 — uncompressed, minified
  • jQuery Core 1.11.0 — uncompressed, minified
  • jQuery Core 1.10.2 — uncompressed, minified
  • jQuery Core 1.10.1 — uncompressed, minified
  • jQuery Core 1.10.0 — uncompressed, minified
  • jQuery Core 1.9.1 — uncompressed, minified
  • jQuery Core 1.9.0 — uncompressed, minified
  • jQuery Core 1.8.3 — uncompressed, minified
  • jQuery Core 1.8.2 — uncompressed, minified
  • jQuery Core 1.8.1 — uncompressed, minified
  • jQuery Core 1.8.0 — uncompressed, minified
  • jQuery Core 1.7.2 — uncompressed, minified
  • jQuery Core 1.7.1 — uncompressed, minified
  • jQuery Core 1.7.0 — uncompressed, minified
  • jQuery Core 1.7.0 — uncompressed, minified
  • jQuery Core 1.6.4 — uncompressed, minified
  • jQuery Core 1.6.3 — uncompressed, minified
  • jQuery Core 1.6.2 — uncompressed, minified
  • jQuery Core 1.6.1 — uncompressed, minified
  • jQuery Core 1.6.0 — uncompressed, minified
  • jQuery Core 1.5.2 — uncompressed, minified
  • jQuery Core 1.5.1 — uncompressed, minified
  • jQuery Core 1.5.0 — uncompressed, minified
  • jQuery Core 1.4.4 — uncompressed, minified
  • jQuery Core 1.4.3 — uncompressed, minified
  • jQuery Core 1.4.2 — uncompressed, minified
  • jQuery Core 1.4.1 — uncompressed, minified
  • jQuery Core 1.4.0 — uncompressed, minified
  • jQuery Core 1.3.2 — uncompressed, minified, packed
  • jQuery Core 1.3.1 — uncompressed, minified, packed
  • jQuery Core 1.3.0 — uncompressed, minified, packed
  • jQuery Core 1.2.6 — uncompressed, minified, packed
  • jQuery Core 1.2.5 — uncompressed, minified, packed
  • jQuery Core 1.2.4 — uncompressed, minified, packed
  • jQuery Core 1.2.3 — uncompressed, minified, packed
  • jQuery Core 1.2.2 — uncompressed, minified, packed
  • jQuery Core 1.2.1 — uncompressed, minified, packed
  • jQuery Core 1.2.0 — uncompressed, minified, packed
  • jQuery Core 1.1.4 — uncompressed, packed
  • jQuery Core 1.1.3 — uncompressed, packed
  • jQuery Core 1.1.2 — uncompressed, packed
  • jQuery Core 1.1.1 — uncompressed, packed
  • jQuery Core 1.1.0 — uncompressed, packed
  • jQuery Core 1.0.4 — uncompressed, packed
  • jQuery Core 1.0.3 — uncompressed, packed
  • jQuery Core 1.0.2 — uncompressed, packed
  • jQuery Core 1.0.1 — uncompressed, packed
  • jQuery Core 1.0.0 — uncompressed, packed

Number

Numbers in JavaScript are double-precision 64-bit format IEEE 754 values. They are immutable primitive values, just like . All operators common in c-based languages are available to work with numbers (+, -, *, /, %, =, +=, -=, *=, /=, ++, —).

1 2

The type of a number is «number».

1 2

Boolean Default

If a number is zero, it defaults to false:

1 2 3 4

Due to the implementation of numbers as double-precision values, the following result is not an error:

1

JavaScript provides utilities to work with numbers in the Math object:

1 2

Parsing Numbers

parseInt and parseFloat help parsing strings into numbers. Both do some implicit conversion if the base isn’t specified:

1 2 3 4 5 6

Numbers to Strings

When appending numbers to string, the result is always a string. The operator is the same, so be careful: If you want to add numbers and then append them to a string, put parentheses around the numbers:

1 2 3 4

Or you use the String class provided by javascript, which try to parse a value as string:

1 2

NaN and Infinity

Parsing something that isn’t a number results in NaN. isNaN helps to detect those cases:

1 2

Division by zero results in Infinity:

1

Both NaN and Infinity are of type «number»:

1 2

Note that NaN compares in a strange way:

1

But:

1

Integer

An integer is a plain Number type, but whenever explicitly mentioned, indicates that a non-floating-point number is expected.

Float

A float is a plain Number type, just as Integer, but whenever explicitly mentioned, indicates that a floating-point number is expected.

Advanced features

Variables are an absolute necessity in most programming languages, but they’re relegated to an «advanced feature» in jq.

In most languages, variables are the only means of passing around data. If you calculate a value, and you want to use it more than once, you’ll need to store it in a variable. To pass a value to another part of the program, you’ll need that part of the program to define a variable (as a function parameter, object member, or whatever) in which to place the data.

It is also possible to define functions in jq, although this is is a feature whose biggest use is defining jq’s standard library (many jq functions such as and are in fact written in jq).

Finally, jq has a operation, which is very powerful but a bit tricky. Again, it’s mostly used internally, to define some useful bits of jq’s standard library.

Event names and namespaces

Any event names can be used for the argument. jQuery will pass through the browser’s standard JavaScript event types, calling the function when the browser generates events due to user actions such as . In addition, the method can trigger both standard browser event names and custom event names to call attached handlers. Event names should only contain alphanumerics, underscore, and colon characters.

An event name can be qualified by event namespaces that simplify removing or triggering the event. For example, defines both the myPlugin and simple namespaces for this particular click event. A click event handler attached via that string could be removed with or without disturbing other click handlers attached to the elements. Namespaces are similar to CSS classes in that they are not hierarchical; only one name needs to match. Namespaces beginning with an underscore are reserved for jQuery’s use.

In the second form of , the argument is a plain object. The keys are strings in the same form as the argument with space-separated event type names and optional namespaces. The value for each key is a function (or value) that is used as the instead of the final argument to the method. In other respects, the two forms are identical in their behavior as described below.

Invoking jq

jq filters run on a stream of JSON data. The input to jq is parsed as a sequence of whitespace-separated JSON values which are passed through the provided filter one at a time. The output(s) of the filter are written to standard out, again as a sequence of whitespace-separated JSON data.

Note: it is important to mind the shell’s quoting rules. As a general rule it’s best to always quote (with single-quote characters) the jq program, as too many characters with special meaning to jq are also shell meta-characters. For example, will fail on most Unix shells because that will be the same as , which will generally fail because . When using the Windows command shell (cmd.exe) it’s best to use double quotes around your jq program when given on the command-line (instead of the option), but then double-quotes in the jq program need backslash escaping.

You can affect how jq reads and writes its input and output using some command-line options:

—version:

Output the jq version and exit with zero.

—slurp/-s:

Instead of running the filter for each JSON object in the input, read the entire input stream into a large array and run the filter just once.

—online-input/-I:

When the top-level input value is an array produce its elements instead of the array. This allows on-line processing of potentially very large top-level arrays’ elements.

—raw-input/-R:

Don’t parse the input as JSON. Instead, each line of text is passed to the filter as a string. If combined with , then the entire input is passed to the filter as a single long string.

—null-input/-n:

Don’t read any input at all! Instead, the filter is run once using as the input. This is useful when using jq as a simple calculator or to construct JSON data from scratch.

—compact-output / -c:

By default, jq pretty-prints JSON output. Using this option will result in more compact output by instead putting each JSON object on a single line.

—color-output / -C and —monochrome-output / -M:

By default, jq outputs colored JSON if writing to a terminal. You can force it to produce color even if writing to a pipe or a file using , and disable color with .

—ascii-output / -a:

jq usually outputs non-ASCII Unicode codepoints as UTF-8, even if the input specified them as escape sequences (like «\u03bc»). Using this option, you can force jq to produce pure ASCII output with every non-ASCII character replaced with the equivalent escape sequence.

—unbuffered

Flush the output after each JSON object is printed (useful if you’re piping a slow data source into jq and piping jq’s output elsewhere).

—sort-keys / -S:

Output the fields of each object with the keys in sorted order.

—raw-output / -r:

With this option, if the filter’s result is a string then it will be written directly to standard output rather than being formatted as a JSON string with quotes. This can be useful for making jq filters talk to non-JSON-based systems.

-f filename / —from-file filename:

Read filter from the file rather than from a command line, like awk’s -f option. You can also use ‘#’ to make comments.

-e / —exit-status:

Sets the exit status of jq to 0 if the last output values was neither nor , 1 if the last output value was either or , or 4 if no valid result was ever produced. Normally jq exits with 2 if there was any usage problem or system error, 3 if there was a jq program compile error, or 0 if the jq program ran.

—arg name value:

This option passes a value to the jq program as a predefined variable. If you run jq with , then is available in the program and has the value .

—argfile name filename:

Passing data to the handler

If a argument is provided to and is not or , it is passed to the handler in the property each time an event is triggered. The argument can be any type, but if a string is used the must either be provided or explicitly passed as so that the data is not mistaken for a selector. Best practice is to use a plain object so that multiple values can be passed as properties.

As of jQuery 1.4, the same event handler can be bound to an element multiple times. This is especially useful when the feature is being used, or when other unique data resides in a closure around the event handler function. For example:

1 2 3 4 5 6 7 8 9

The above code will generate two different alerts when the button is clicked.

As an alternative or in addition to the argument provided to the method, you can also pass data to an event handler using a second argument to or . Data provided this way is passed to the event handler as further parameters after the object. If an array was passed to the second argument of or , each element in the array will be presented to the event handler as an individual parameter.

Event performance

In most cases, an event such as occurs infrequently and performance is not a significant concern. However, high frequency events such as or can fire dozens of times per second, and in those cases it becomes more important to use events judiciously. Performance can be increased by reducing the amount of work done in the handler itself, caching information needed by the handler rather than recalculating it, or by rate-limiting the number of actual page updates using .

Attaching many delegated event handlers near the top of the document tree can degrade performance. Each time the event occurs, jQuery must compare all selectors of all attached events of that type to every element in the path from the event target up to the top of the document. For best performance, attach delegated events at a document location as close as possible to the target elements. Avoid excessive use of or for delegated events on large documents.

jQuery can process simple selectors of the form very quickly when they are used to filter delegated events. So, , , and are all fast selectors. Delegated events that use more complex selectors, particularly hierarchical ones, can be several times slower—although they are still fast enough for most applications. Hierarchical selectors can often be avoided simply by attaching the handler to a more appropriate point in the document. For example, instead of use .

link Downloading jQuery

Compressed and uncompressed copies of jQuery files are available. The uncompressed file is best used during development or debugging; the compressed file saves bandwidth and improves performance in production. You can also download a sourcemap file for use when debugging with a compressed file. The map file is not required for users to run jQuery, it just improves the developer’s debugger experience. As of jQuery 1.11.0/2.1.0 the comment is not included in the compressed file.

To locally download these files, right-click the link and select «Save as…» from the menu.

jQuery

For help when upgrading jQuery, please see the upgrade guide most relevant to your version. We also recommend using the jQuery Migrate plugin.

You can also use the slim build, which excludes the ajax and effects modules:

Object

Everything in JavaScript is an object, though some are more objective (haha). The easiest way to create an object is the object literal:

1 2 3 4 5

The type of an object is «object»:

1

You can write and read properties of an object using the dot notation:

1 2 3 4

Array Notation

Or you write and read properties using the array notation, which allows you to dynamically choose the property:

1 2 3 4 5 6 7

Iteration

Iterating over objects is easy with the for-in-loop:

1 2 3 4 5 6 7

Note that for-in-loop can be spoiled by extending Object.prototype (see Object.prototype is verboten) so take care when using other libraries.

jQuery provides a generic each function to iterate over properties of objects, as well as elements of arrays:

1 2 3

The drawback is that the callback is called in the context of each value and you therefore lose the context of your own object if applicable. More on this below at Functions.

An object, no matter if it has properties or not, never defaults to false:

1 2

Prototype

All objects have a prototype property. Whenever the interpreter looks for a property, it also checks in the object’s prototype if the property is not found on the object itself. jQuery uses the prototype extensively to add methods to jQuery instances. Internally, jQuery makes an alias of so you can use either one (though plugin developers have standardized on ).

1 2 3 4 5 6 7 8 9 10 11 12 13 14

С этим читают