Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Заметки JQuery.docx
Скачиваний:
2
Добавлен:
29.09.2019
Размер:
41.8 Кб
Скачать

JQuery

jQuery — библиотека JavaScript, фокусирующаяся на взаимодействии JavaScript и HTML. Библиотека jQuery помогает легко получать доступ к любому элементу DOM, обращаться к атрибутам и содержимому элементов DOM, манипулировать ими. Также библиотека jQuery предоставляет удобный API по работе с Ajax.

_____________________________________________________________________________________

Подключение JQuery с помощью google

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">

_____________________________________________________________________________________

Функция, вызываемая при готовности страницы

$('document').ready( "Now we are anonymous!");

//by the way, you've seen $('document').ready(...)

//before. It is very common in jQuery - the function

//that is passed to `ready` is run when the HTML document

//is ready for javascript to start happening

Методу .ready можно придавать и значение любой функции JS.

_____________________________________________________________________________________

.proxy

jQuery.proxy( function, context )

function The function whose context will be changed.

Context The object to which the context (this) of the function should be set.

JQuery.Proxy( context, name )

context The object to which the context of the function should be set.

Name The name of the function whose context will be changed (should be a property of the context object).

This method is most useful for attaching event handlers to an element where the context is pointing back to a different object. Additionally, jQuery makes sure that even if you bind the function returned from jQuery.proxy() it will still unbind the correct function if passed the original.

_____________________________________________________________________________________

Jquery() или $()

The function jQuery() is the most important one in the jQuery library. You will almost always use it through the shortcut, $()

This function has many uses, all of which return a jQuery object.

The most simple use is to turn a regular javascript HTML element into a jQuery one.

var element = document.getElementById('myElement');

//element is now a plain old javascript DOM element

//make element a jQuery object

$element = element;

_____________________________________________________________________________________

Селекторы

The most simple selector selects by tag name. So $('span') would select every span element on the page.

//select all the divs on the page

$allOfTheDivs = $('div');

//select all the links on the page

$allOfTheLinks = $('a');

Passing a tag name as a string to $() will return a jQuery object containing every element that is that type of element.

_____________________________________________________________________________________

Селекторы по id

$element = $('#elementId')

Пример:

//assign $contentDiv to the jQuery object

//containing the div with id contentDiv

$contentDiv = $('#contentDiv');

//assign $entryBox to the jQuery object

//containing the textbox with id entryBox

$entryBox = $('#entryBox');

_____________________________________________________________________________________

Селектор классов

$('.my-class')

//select elements of the class 'important'

$importantElements = $('.important');

//select elements of the class 'active'

$activeElements = $('.active');

_____________________________________________________________________________________

Все селекторы

Borrowing from CSS 1–3, and then adding its own, jQuery offers a powerful set of tools for matching a set of elements in a document.

If you wish to use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[\]^`{|}~ ) as a literal part of a name, you must escape the character with two backslashes: \\. For example, if you have an element with id="foo.bar", you can use the selector $("#foo\\.bar"). The W3C CSS specification contains the complete set of rules regarding valid CSS selectors. Also useful is the blog entry by Mathias Bynens on CSS character escape sequences for identifiers.

  • All Selector (“*”)

Basic

Selects all elements.

  • :Animated Selector

Basic Filter, jQuery Extensions

Select all elements that are in the progress of an animation at the time the selector is run.

  • Attribute Contains Prefix Selector [name|="value"]

Attribute

Selects elements that have the specified attribute with a value either equal to a given string or starting with that string followed by a hyphen (-).

  • Attribute Contains Selector [name*="value"]

Attribute

Selects elements that have the specified attribute with a value containing the a given substring.

  • Attribute Contains Word Selector [name~="value"]

Attribute

Selects elements that have the specified attribute with a value containing a given word, delimited by spaces.

  • Attribute Ends With Selector [name$="value"]

Attribute

Selects elements that have the specified attribute with a value ending exactly with a given string. The comparison is case sensitive.

  • Attribute Equals Selector [name="value"]

Attribute

Selects elements that have the specified attribute with a value exactly equal to a certain value.

  • Attribute Not Equal Selector [name!="value"]

Attribute, jQuery Extensions

Select elements that either don't have the specified attribute, or do have the specified attribute but not with a certain value.

  • Attribute Starts With Selector [name^="value"]

Attribute

Selects elements that have the specified attribute with a value beginning exactly with a given string.

  • :button Selector

Deprecated, Form, jQuery Extensions

Selects all button elements and elements of type button.

  • :checkbox Selector

Deprecated, Form, jQuery Extensions

Selects all elements of type checkbox.

  • :checked Selector

Form

Matches all elements that are checked.

  • Child Selector (“parent > child”)

Hierarchy

Selects all direct child elements specified by "child" of elements specified by "parent".

  • Class Selector (“.class”)

Basic

Selects all elements with the given class.

  • :contains() Selector

Content Filter

Select all elements that contain the specified text.

  • Descendant Selector (“ancestor descendant”)

Hierarchy

Selects all elements that are descendants of a given ancestor.

  • :disabled Selector

Form

Selects all elements that are disabled.

  • Element Selector (“element”)

Basic

Selects all elements with the given tag name.

  • :empty Selector

Content Filter

Select all elements that have no children (including text nodes).

  • :enabled Selector

Form

Selects all elements that are enabled.

  • :eq() Selector

Basic Filter, jQuery Extensions

Select the element at index n within the matched set.

  • :even Selector

Basic Filter, jQuery Extensions

Selects even elements, zero-indexed. See also odd.

  • :file Selector

Deprecated, Form, jQuery Extensions

Selects all elements of type file.

  • :first-child Selector

Child Filter

Selects all elements that are the first child of their parent.

  • :first Selector

Basic Filter, jQuery Extensions

Selects the first matched element.

  • :focus selector

Basic Filter, Form

Selects element if it is currently focused.

  • :gt() Selector

Basic Filter, jQuery Extensions

Select all elements at an index greater than index within the matched set.

  • Has Attribute Selector [name]

Attribute

Selects elements that have the specified attribute, with any value.

  • :has() Selector

Content Filter, jQuery Extensions

Selects elements which contain at least one element that matches the specified selector.

  • :header Selector

Basic Filter, jQuery Extensions

Selects all elements that are headers, like h1, h2, h3 and so on.

  • :hidden Selector

jQuery Extensions, Visibility Filter

Selects all elements that are hidden.

  • ID Selector (“#id”)

Basic

Selects a single element with the given id attribute.

  • :image Selector

Deprecated, Form, jQuery Extensions

Selects all elements of type image.

  • :input Selector

Deprecated, Form, jQuery Extensions

Selects all input, textarea, select and button elements.

  • :last-child Selector

Child Filter

Selects all elements that are the last child of their parent.

  • :last Selector

Basic Filter, jQuery Extensions

Selects the last matched element.

  • :lt() Selector

Basic Filter, jQuery Extensions

Select all elements at an index less than index within the matched set.

  • Multiple Attribute Selector [name="value"][name2="value2"]

Attribute

Matches elements that match all of the specified attribute filters.

  • Multiple Selector (“selector1, selector2, selectorN”)

Basic

Selects the combined results of all the specified selectors.

  • Next Adjacent Selector (“prev + next”)

Hierarchy

Selects all next elements matching "next" that are immediately preceded by a sibling "prev".

  • Next Siblings Selector (“prev ~ siblings”)

Hierarchy

Selects all sibling elements that follow after the "prev" element, have the same parent, and match the filtering "siblings" selector.

  • :not() Selector

Basic Filter

Selects all elements that do not match the given selector.

  • :nth-child() Selector

Child Filter

Selects all elements that are the nth-child of their parent.

  • :odd Selector

Basic Filter, jQuery Extensions

Selects odd elements, zero-indexed. See also even.

  • :only-child Selector

Child Filter

Selects all elements that are the only child of their parent.

  • :parent Selector

Content Filter, jQuery Extensions

Select all elements that are the parent of another element, including text nodes.

  • :password Selector

Deprecated, Form, jQuery Extensions

Selects all elements of type password.

  • :radio Selector

Deprecated, Form, jQuery Extensions

Selects all elements of type radio.

  • :reset Selector

Deprecated, Form, jQuery Extensions

Selects all elements of type reset.

  • :selected Selector

Form, jQuery Extensions

Selects all elements that are selected.

  • :submit Selector

Deprecated, Form, jQuery Extensions

Selects all elements of type submit.

  • :text Selector

Deprecated, Form, jQuery Extensions

Selects all elements of type text.

  • :visible Selector

jQuery Extensions, Visibility Filter

Selects all elements that are visible.

_____________________________________________________________________________________

  • Descendent Selector

$("div .thingy")

will select all elements that have the class 'thingy' that are a descendent of a div element

  • Child Selector

$(".thingy > a")

will select all links that are the child of an element with the class 'thingy'

  • Pseudo-Classes

$("li:first-child")

will select all list-elements that are the first child of their parent.

//select the 'lorem ipsum' paragraph

$loremIpsumP = $("#info>p");

//select all list items that are in the 'info' div

$infoListItems = $('#info li');

_____________________________________________________________________________________

.add()

Метод .add() находит элементы, заданные с помощью входного параметра, или создает их на лету. А затем добавляет найденные (или созданные) элементы к исходному набору jQuery и возвращает модифицированный (объединенный) набор jQuery.

$h1elements = $("h1");

//use add to add the h2 elements to $h1elements

$h1andH2elements = $h1elements.add("h2");

  1. Примечание:

С помощью метода .add() можно объединять селекторы по условию ИЛИ. Например,  $('div').add('p')  идентично  $('div, p').

  1. Примечание:

При использовании метода .add() в jQuery 1.4 с двумя параметрами (когда вторым аргументом передается context), необходимо помнить, что в данном случае первый аргумент должен быть только селектором jQuery.

 // Сначала установим желтый цвет фона для всех элементов

// <div> в документе, а затем установим красную границу

// вокруг всех элементов <div> и <p>.

$('div').css('background', 'yellow').add('p').css('border',

'2px solid red');

  

// Сначала создаем набор jQuery всех элементов <div>

// на странице, затем создаем новый элемент <p>, добавляем

// его в набор jQuery (но не в DOM-дерево!), а потом добавляем

// ко всем элементам набора сласс с именем blue.

$('div').add('<p>Новый абзац</p>').addClass('blue');

_____________________________________________________________________________________