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

Вставить перед и после объекта, который их вызывает.

То же, что и append() для appendTo(). //Insert a div with content 'before' and class 'before'

//before $divToInsertAround using .before

$divToInsertAround.before('<div class="before">before</div>');

//Insert a div with content 'after' and class 'after'

//to $divToInsertAround using .after

$divToInsertAround.after('<div class="after">after</div>');

_____________________________________________________________________________________

Wrap() ()

wrap() will wrap each element of the jQuery object on which it is called in a copy of the jQuery object or HTML string passed to it.

For example,

$('a').wrap($('<span/>'))

will wrap every <a> in a <span>.

$('div.wrapMe').wrap($("<div class='wrapper'></div>"));

_____________________________________________________________________________________

//move the div with id 'lineJumper'

//to be the first child of 'line'

$('#lineJumper').prependTo($('#line'));

//move the div with id 'lineLeaver'

//out of the line (make it a sibling of the line)

$('div#line').after($('div#lineLeaver'));

_____________________________________________________________________________________

.clone()

.clone() returns a deep copy of the element on which it is called.

That means that you get a new copy of the element itself, but also all of its children (and their children, et cetera).

If you call .clone(true), all of the elements' events, attributes, and data are cloned too.

//write this function as described

//in the exercise instructions

//remember that we want to clone

//data and events, too!

function cloneAndAppend($elementToClone, $elementToAppendItTo) {

$elementToAppendItTo.append($elementToClone.clone(true));

}

_____________________________________________________________________________________

.empty()

empty() removes every element that is a descendent of the element on which it is called. Before it deletes the element, it removes events and data for memory-safety.

$('document').ready(function() {

$('#emptyTrash').click(function() {

//write code that calls

//empty on the div with id 'trash'

$('#trash').empty();

});

});

Пример:

_____________________________________________________________________________________

.remove()

remove() lets you remove one specific element, or use a selector to remove only specific descendants of an element.

For example,

$('div li').remove()

will remove all <li>s that are a descendent of $myElement.

And

$myElement.remove()

will remove $myElement itself.

$('document').ready(function() {

$('#emptyTrash').click(function() {

//remove the element with id 'third-div'

$('#third-div').remove();

//remove all decendants of the element with id 'first-div'

//that have the class 'removeMe'; For this exercise put

//nothing in the actual remove() tag

$('#first-div .removeMe').remove();

});

});

Важно

Для указания ИД и класса объекта одновременно нужно отделить их пробелом:

$('#first-div .removeMe').remove();

_____________________________________________________________________________________

.removeData()

removeData() takes a key as a parameter, and deletes the data value stored at that key.

$('div.square').removeData('jumpedPieces');

_____________________________________________________________________________________

:odd() :even()

:odd() - Поиск нечетных элементов, начиная с нуля.

:even() - Поиск четных элементов, начиная с нуля.

$("tr:odd").css("background-color", "#bbbbff");

$('#right li:odd').remove();

_____________________________________________________________________________________

JQuery Events

_____________________________________________________________________________________

.click()

Bind an event handler to the "click" JavaScript event, or trigger that event on an element.

$('#clickMe').click(function(){

$("#changeMe").html("I have been changed");

});

_____________________________________________________________________________________

.on()

Example with click:

$('#clickMe').on("click", function(){ alert("I have been clicked!"); });

$(document).on("ready", function(){

message = "iiiiii'm ready!";

alert(message);

});

_____________________________________________________________________________________

.dblclick()

$('#target').dblclick(function() {

alert('Handler for .dblclick() called.');

});

_____________________________________________________________________________________

.mouseenter() и .mouseleave()

Данное событие обычно активируется единожды,  когда указатель мыши находится в центре элемента.

$("div.overout").mouseenterer(function(){

_____________________________________________________________________________________

Multiple Handlers

$('document').ready(function(){

$(document).on({

mousedown: function() {

$("#lastClick").html("down");

},

mouseup: function() {

$("#lastClick").html("up");

}

});

});

_____________________________________________________________________________________

event.target

Свойство target экземпляра объекта Event идентифицирует элемент - инициатор события (т.е. узел, в котором произошло событие и с которого началась фаза всплывания). Не путать с event.currentTarget.

$(event.target)

$('li').click(function(event){

var $target = $(event.target);

alert($target.id);

});

$(document).ready(function(){

$('div').click((function(event) {

var $target = $(event.target);

if ($target.hasClass("blue")) {

$target.removeClass();

$target.addClass("green");

}

else if ($target.hasClass("green")) {

$target.removeClass();

$target.addClass("yellow");

}

else if ($target.hasClass("yellow")) {

$target.removeClass();

$target.addClass("blue");

}

}));

});

Изменяет цвет квадрата при клике

_____________________________________________________________________________________

.mousemove()

Назначает функцию к событию mousemove для каждого элемента набора.

Данное событие обычно активируется, когда указатель двигается над областью элемента. Обработчику события передается одна переменная — объект события. В свойствах .clientX и .clientY находятся координаты указателя.

_____________________________________________________________________________________

.offset

Возвращаемый объект содержит два значение (сверху и слева) типа Float. Для фактического позиционирования браузеры обычно округляют эти значения до ближайшего целого. Этот метод работает только с видимыми элементами.

 .offset( coordinates )

Coordinates An object containing the properties top and left, which are integers indicating the new top and left coordinates for the elements.

 offset( function(index, coords) )

function(index, coords) A function to return the coordinates to set. Receives the index of the element in the collection as the first argument and the current coordinates as the second argument. The function should return an object with the new top and left properties.

$(document).ready(function(){

$(document).mousemove(function(event){

$('#mouseFollow').offset({top:event.pageY,left:event.pageX});

});

}); квадратик преследует курсор

_____________________________________________________________________________________

:hover()

$(document).ready(function(){

$("div").hover(

function () {

$(this).addClass('hover');

},

function () {

$(this).removeClass('hover');

}

);

});

_____________________________________________________________________________________

Keypress()

$(document).ready(function(){

$('body').keypress(function(){

$('div#boxDiv').append('<div class="box" />'); });

});

При нажатии добавляет красный квадрат в строку.

_____________________________________________________________________________________

Focus() и blur()

When the user starts using an object on the page it is "given" focus and the focus() event is called. When the user is no longer using the object is loses focus and the blur() event is called.

$(document).ready(function(){

$('input').focus(function(){

$(this).addClass('inFocus');

});

$('input').blur(function(){

$(this).removeClass('inFocus');

});

});

При фокусе на строке ввода – бэкграунд – красный.

_____________________________________________________________________________________

.submit() .text() .show() .fadeOut()

При верном ответе высвечивает коррект, при неверном – еррор. Текст исчазет через пару мгновений.

$(document).ready(function(){

$("#form").submit(function(event) {

event.preventDefault();

if($('input').val()==='codecademy'){

$('span').text("Correct!").show().fadeOut(2000);

}

else {

$('span').text("Error!").show().fadeOut(2000);

}

});

});

_____________________________________________________________________________________

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]