Weitere ähnliche Inhalte Ähnlich wie Алексей Бережной — «jQuery» (20) Алексей Бережной — «jQuery»8. Работа с DOM
$(‘.b-page .b-block’).eq(2).addClass(‘b-block_mode_blue’);!
!
!
$(‘.b-block’).find(‘.b-block2’).hide();!
!
!
$(‘.b-text-block’).text(‘hello world!’).css(‘color’, ‘red’);!
!
!
$(‘.b-block’).add(‘.b-block2’).html(‘<b>Bold</b>’);!
!
!
8
9. Работа с DOM
$('<h1/>', {!
style: 'text-align: center',!
html: $('<span/>', {!
style: 'color: red',!
html: 'Я' })})!
.append(' в ШРИ')!
.prependTo('body');!
9
10. AJAX
$.ajax({!
!type: 'POST',!
!dataType: 'json',!
!url: '/registered/main.pl',!
!data: {!
! !name: ’Aleksey Berezhnoy’,!
! !company: ’Yandex’,!
! !position: ’UI developer’!
!},!
!success: function(data){!
! !console.log(’request success’);!
!},!
!error: function(e){!
! !console.log(’Outch!’);!
!}!
}!
10
11. События
$(‘.b-alert-button’).click(function(){!
!alert(‘button pressed’);!
});!
!
!
$(window).resize(function(){!
!console.log($(this).width(), $(this).height());!
});!
!
!
$(‘*’).hover(showHideBeautifulTooltip);!
!
!
$(‘.b-input’).on(‘blur change’, validateInputValue);!
11
14. Селекторы
• Базовые
• Иерархия
• Базовые фильтры
• Фильтры по содержимому
• Фильтры видимости
• Фильтры потомков
• Фильтры атрибутов
• Фильтры элементов формы
14
15. Базовые
• #id
• element
• .class, .class.class
• *
• selector1, selector2
15
16. Иерархия
• ancestor descendant
• parent > child
• prev + next
• prev ~ siblings
16
17. Базовые фильтры
• :eq(index)
• :first
• :gt(index)
• :last
• :lt(index)
• :not(selector)
• :header
• :even
• :animated
• :odd
• :focus
17
20. Фильтры потомков
• :nth-child(expr)
• :first-child
• :last-child
• :only-child
20
21. Фильтры атрибутов
• [attribute]
• [attribute=value]
• [attribute!=value]
• [attribute^=value]
• [attribute$=value]
• [attribute*=value]
• [attribute|=value]
• [attribute~=value]
• [attribute][attribute2]
21
22. Фильтры элементов формы
• :input
• :text
• :password
• :radio
• :checkbox
• :submit
• :image
• :reset
• :button
22
• :file
25. Ядро
• jQuery( selector [ , context ] )
• jQuery( html )
• jQuery( callback )
25
27. jQuery( selector [ , context ] )
$(‘div.foo’);!
!
$(‘div.foo’, this); // ~ $(this).find(‘div.foo’)!
!
27
28. jQuery( html )
$('<p class=”b-block">My <em>new</em> text</p>')!
!.appendTo('body');!
28
30. AJAX
• Низкоуровневый интерфейс
• Сокращения
• Глобальные обработчики ajax события
• Сериализация
30
32. jQuery.ajax( url, [settings] )
$.ajax({!
!url: 'ajax/test.html',!
!success: function(data) {!
! !alert('Load was performed.');!
!}!
});!
32
33. Сокращения
• $.load
• $.get
• $.getJSON
• $.getScript
• $.post
33
35. Сериализация
<form>!
!<input type=“text” name=“name” value=“Aleksey”/>!
!<input type=“text” name=“surname” value=“Berezhnoy”/>!
!<input type=“text” name=“position” value=“UI developer”/>!
!<input type=“hidden” name=“key” value=“42”/>!
</form>!
!
!
{!
!name: 'Aleksey',!
!surname: 'Berezhnoy',!
!position: 'UI developer',!
!key: 42!
}!
!
!
"name=Aleksey&surname=Berezhnoy&position=UI+developer&key=42"!
35
36. Сериализация
• $.serialize
• $.serializeArray
• $.param
36
37. События
• Загрузка страницы
• Обработка событий
• Сокращения
• Объект события
• jQuery special events
37
38. Загрузка страницы
$(document).ready(function(){ /* ... */ });!
!
$(function(){ /* ... */ });!
38
39. Обработка событий
• $.bind / $.unbind
• $.one
• $.trigger
• $.triggerHandler
• $.live / $.die
• $.delegate / $.undelegate
• $.on / $.off
39
40. Сокращения
• $.focus
• $.blur
• $.focusin
• $.change
• $.focusout
• $.click
• $.keydown
• $.dbclick
• $.keypress
• $.error
• $.keyup
40
41. Сокращения
• $.mousedown
• $.load
• $.mouseup
• $.unload
• $.mouseenter
• $.resize
• $.mouseleave
• $.scroll
• $.mousemove
• $.select
• $.mouseout
• $.submit
• $.mouseover
41
42. Объект события
Нормализирует:
• target
• relatedTarget
• pageX
• pageY
• which
• metaKey
var e = $.Event(‘keydown’, { keyCode: 64 });!
!
$(‘body’).trigger( e );!
42
43. jQuery special events
Домашнее задание:
Напишите плагин для jQuery, позволяющий
добавить обработчик события на DOM-
элемент, срабатывающий на:
• нажатие только левой кнопки мыши
• тройное нажатие
43
44. Эффекты
• Базовые
• Скольжение (Sliding)
• Исчезновение (Fading)
• Произвольные анимации
• Настройки
44
45. Базовые
• $.show
• $.hide
• $.toggle
45
50. Атрибуты
• Атрибуты
• Класс
• HTML, текст
• Значение
50
51. Атрибуты
• $.attr
• $.removeAttr
• $.prop
• $.removeProp
51
52. $.attr vs $.prop
<input type=“checkbox” checked=“checked” />!
true
(Boolean)
Изменится
с
состоянием
elem.checked
чекбокса
true
(Boolean)
Изменится
с
состоянием
$(elem).prop("checked")
чекбокса
"checked"
(String)
Начальное
состояние
elem.getA8ribute("checked")
чекбокса,
не
меняется
$(elem).a8r("checked")
(1.6)
"checked"
(String)
Начальное
состояние
чекбокса,
не
меняется
$(elem).a8r("checked")
(1.6.1+)
"checked"
(String)
Изменится
с
состоянием
чекбокса
$(elem).a8r("checked")
(pre-‐1.6)
true
(Boolean)
Изменится
с
состоянием
чекбокса
52
clck.ru/2j90t
53. Класс
• $.addClass
• $.hasClass
• $.removeClass
• $.toggleClass
53
56. CSS
• CSS
• Позиционирование
• Высота и ширина
56
58. Позиционирование
• $.offset
• $.offsetParent
• $.position
• $.scrollTop
• $.scrollLeft
58
59. Высота и ширина
• $.height
• $.width
• $.innerHeight
• $.innerWidth
• $.outerHeight
• $.outerWidth
59
61. Фильтрование
• $.eq
• $.first
• $.last
• $.has
• $.filter
• $.is
• $.map
• $.not
• $.slice
61
62. Перемещение по дереву
• $.offsetParent
• $.children • $.parent
• $.closest • $.parents
• $.find • $.parentsUntil
• $.next • $.prev
• $.nextAll • $.prevAll
• $.nextUntil • $.prevUntil
• $.siblings
62
63. Прочее
• $.add
• $.andSelf
• $.contents
• $.end
63
64. Манипуляции
• Вставка внутрь
• Вставка снаружи
• Оборачивание
• Замена
• Удаление
• Копирование
64
65. Вставка внутрь
• $.append
• $.appendTo
• $.prepend
• $.prependTo
65
66. Вставка снаружи
• $.after
• $.before
• $.insertAfter
• $.insertBefore
66
67. Оборачивание
• $.unwrap
• $.wrap
• $.wrapAll
• $.wrapInner
67
68. Замена
• $.replaceWith
• $.replaceAll
68
69. Удаление
• $.detach
• $.empty
• $.remove
69
71. Deffered
• def.always
• def.progress
• def.done
• def.reject
• def.fail
• def.rejectWith
• def.isRejected
• def.resolve
• def.isResolved
• defresolveWith
• def.notify
• def.state
• def.notifyWith
• def.then
• def.pipe
• def.promise
71
72. Callbacks
• cb.add(callbacks)
• cb.disable()
• cb.empty()
• cb.fire(arguments)
• cb.fired()
• cb.fireWith([context] [, args]) • $.Callbacks
• cb.has(callback)
• cb.lock()
• cb.locked()
72
• cb.remove(callbacks)
73. Callbacks
function fn1( value ){!
console.log( value );!
}!
!
function fn2( value ){!
fn1("fn2 says:" + value);!
return false;!
}!
!
var callbacks = $.Callbacks();!
!
callbacks.add( fn1 );!
callbacks.fire( "foo!" ); // foo!!
!
callbacks.add( fn2 );!
callbacks.fire( "bar!" ); // bar!, fn2 says: bar!!
73
74. Утилиты
• Определение браузера и возможностей
• Базовые операции
• Функции для работы с data
• Операции проверки
74
76. Базовые операции
• $.each • $.merge
• $.extend • $.noop
• $.grep • $.proxy
• $.makeArray • $.unique
• $.map • $.trim
• $.inArray • $.parseJSON
76
77. Функции для работы с data
• $.queue
• $.clearQueue
• $.dequeue
• $.data
• $.removeData
77
78. Операции проверки
• $.type
• $.isArray
• $.isEmptyObject
• $.isFunction
• $.isPlainObject
• $.isWindow
• $.isNumeric
78
80. Рекомендации
• Chainability
• Кеширование
• Использование API
• Плагины
80
81. Chainability
$(‘.b-block’).html(‘<span class=“b-block__inner”></span>’);!
!
$(‘.b-block’).find(‘.b-block__inner’).css(‘color’, ‘blue’);!
!
$(‘.b-block’).find(‘.b-block__inner’).text(‘hello’);!
!
$(‘.b-block’).css(‘background’, ‘green’);!
!
$(‘.b-block’).click(function(){!
!console.log(‘b-block clicked’);!
});!
81
82. Chainability
$(‘.b-block’).html(‘<span class=“b-block__inner”></span>’);!
!
$(‘.b-block’).find(‘.b-block__inner’).css(‘color’, ‘blue’);!
!
$(‘.b-block’).find(‘.b-block__inner’).text(‘hello’);!
!
$(‘.b-block’).css(‘background’, ‘green’);!
!
$(‘.b-block’).click(function(){!
!console.log(‘b-block clicked’);!
});!
82
83. Chainability
$(‘.b-block’)!
!.html(‘<span class=“b-block__inner”></span>’)!
!.find(‘.b-block__inner’)!
! !.css(‘color’, ‘blue’)!
! !.text(‘hello’)!
! !.end() // а вот и end!
!.css(‘background’, ‘green’)!
!.click(function(){!
! !console.log(‘b-block clicked’);!
!});!
83
84. Кеширование
$(‘b-action’)!
!.mouseenter(function(){!
! !$(‘b-signal’).addClass(‘b-signal_mode_mouseenter’);!
!})!
!.mouseleave(function(){!
! !$(‘b-signal’).addClass(‘b-signal_mode_mouseleave’);!
!})!
!.click(function(){!
! !$(‘b-signal’).addClass(‘b-signal_mode_click’);!
!});!
!
!
!
!
!
84
85. Кеширование
$(‘b-action’)!
!.mouseenter(function(){!
! !$(‘b-signal’).addClass(‘b-signal_mode_mouseenter’);!
!})!
!.mouseleave(function(){!
! !$(‘b-signal’).addClass(‘b-signal_mode_mouseleave’);!
!})!
!.click(function(){!
! !$(‘b-signal’).addClass(‘b-signal_mode_click’);!
!});!
!
!
!
!
!
85
86. Кеширование
var bSignal = $(‘b-signal’);!
!
$(‘b-action’)!
!.mouseenter(function(){!
! !bSignal.addClass(‘b-signal_mode_mouseenter’);!
!})!
!.mouseleave(function(){!
! !bSignal.addClass(‘b-signal_mode_mouseleave’);!
!})!
!.click(function(){!
! !bSignal.addClass(‘b-signal_mode_click’);!
!});!
!
!
!
!
!
86
87. Использование API
!
document.onclick = function(e) {!
!...!
};!
!
$(function() {!
!...!
});!
!
!
$(document).ready(function() {!
!var promoItem = document.getElementById(‘promo-item’);!
!!
!...!
!
});!
87
88. Использование API
$(‘.jsbanner’).each(function() {!
!var externalScript = document.createElement(‘script’);!
!
!externalScript.type = ‘text/javascript’;!
!
!externalScript.onreadystatechange = function () {!
! !if (this.readyState == 'loaded’) {!
! ! !onLoadScript.apply(this);!
! !}!
!}!
!
!externalScript.onload = onLoadScript;!
!
!var path = this.getAttribute('path');!
!if(path) {!
! !externalScript.src = path;!
! !this.appendChild(externalScript);!
!}!
});!
88