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

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

.find( expression )

expression – (строка | элемент | объект jQuery)

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

Функция возвращает новый набор jQuery, не изменяя первоначальный набор.

//find descendents of the div with id 'divOne'

//that are span elements

$spanDescendants = $('#divOne').find('span');

.find(*) – выбирает все элементы дочерного набора.

_____________________________________________________________________________________

parent() и parents()

$that.parent(); - selects the jQuery object that is the direct parent of each element in the jQuery object on which it is called. $that.parents(); - selects every element that is above each element in the jQuery object on which it is called - it will select parents, grandparents, and so on.

_____________________________________________________________________________________

.closest()

$("#lBlock").closest("div") - будет искать первый div-элемент среди элемента с id = lBlock и всех его предков.

$(".lBlock").closest("div") - для каждого элемента с классом lBlock будет искать первый div-элемент среди самого элемента и его предков.

closest()Начинает поиск непосредственно с выбранного (выбранных) элемента и движется вверх по иерархии. Двигаясь вверх по иерархии останавливает поиск после первого подходящего элемента (после чего начинает осуществлять поиск для следующего выбранного элемента). Поэтому, находит не более одного элемента для каждого из выбранных.

_____________________________________________________________________________________

Siblings() (родной брат)

Description:

The siblings( [selector] ) method gets a set of elements containing all of the unique siblings (родные братья) of each of the matched set of elements.

Syntax:

Here is the simple syntax to use this method:

selector.siblings( [selector] )

Parameters:

Here is the description of all the parameters used by this method:

  • selector: This is optional selector to filter the sibling Elements with.

$that.siblings();

_____________________________________________________________________________________

html()

you can insert new elements into the page using the jQuery .html()

$myElement.html()set

It will get and return the current html contents of the selected element. But called with a string argument, like this: $myElement.html("<b>Hi</b>");

It will set the html content of the selected element to the string (in this case, 'Hi').

Ex.: Write a function fillHTML() that takes two jQuery objects. It should set the html of the first one to the html of the second one.

function fillHTML($sink,$source) {

$sink.html($source.html());

}

_____________________________________________________________________________________

Height() и width()

$element.height(50) will set the height to 50 pixels (pixels are the default unit).

Повернуть на 90 градусов: function rotate($that) {

//swap the height and width attributes

//of $that using .height and .width;

var $x = $that.height();

$that.height($that.width());

$that.width($x);

}

_____________________________________________________________________________________

Css()

$myElement.css('margin-left',20)

http://www.codecademy.com/ru/courses/basic-jquery/3#!/exercises/2

_____________________________________________________________________________________

Css Classes

  • addClass(): adds the class passed as an argument

  • removeClass(): removes the class or list of classes passed in. If it is called without an argument, all classes are removed;

  • hasClass(): check if an element has a class (returns true or false)

  • toggleClass(): Adds a class if it is not there, remove it if it is.

Ex.: Write two functions:

  1. toggleClass which takes a jQuery object and the name of the class and calls toggleClass on the object

  2. setExclusiveClass which also takes a jQuery object and a class, and makes it such that the elements in the object passed have only the class given.

1. function toggleClass($that,className) {

$that.toggleClass(className);

}

2. function setExclusiveClass($that,className) {

$that.removeClass();

return $that.addClass(className);

}

_____________________________________________________________________________________

.each()

There are two versions of each(): one is a method of $, and the other is a method of the jQuery object. They behave very similarly.z

The method $.each() takes two arguments: an object and a function. It calls the function for every key/value (index/value if its an array) pair in the object.

For example:

$.each([1,2,3,4],function(index,value) { alert(value); });

will open four alerts, the first with '1', the second with '2', etc.

When you call .each() on a jQuery object, it takes one argument (the function) and is the same as calling $.each() with the jQuery object as the first argument.

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

$collection.each(f);. $collection is an array, and f is a function that does something on each element in the array.

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

Цикл можно остановить в любой момент, вернув из функции обратного вызова false.

$('li').each(function(i,elem) {

if ($(this).is(".stop")) {

alert("Остановлено на " + i + "-м пункте списка.");

return false;

} else {

alert(i + ': ' + $(elem).text());

});

_____________________________________________________________________________________

.click()

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

_____________________________________________________________________________________

Шашки

Script.js function setUpPieces() {

//select all the divs with class 'piece'

//add the 'light' class to half of them

//add the 'dark' to the other half

$('div.piece:even').addClass("dark");

$('div.piece:odd').addClass("light");

}

function movePieceTo($piece,newTop,newLeft) {

//set the css 'top' and 'left'

//attributes of the passed piece

//to the arguments newTop and newLeft

$piece.css('top', newTop);

$piece.css('left', newLeft);

}

function setUpBoard() {

//iterate through all of the divs

//with class `square`

//figure out whether each one should be

//light or dark, and assign the proper class

$('div.square').each(function(index,square){

$square = $(square);

if (!lightOrDark(index)){

$square.addClass('light');

}else {

$square.addClass('dark');

}

});

//heres a helper function that takes a number between

//0 and 63 (inclusive) and returns 1 if the square should be

//dark, and 0 if the square should be light

function lightOrDark(index) {

var x = index % 8;

var y = Math.floor(index / 8);

var oddX = x % 2;

var oddY = y % 2;

return (oddX ^ oddY);

}

}

function toggleSelect($piece) {

//if $piece has the class 'selected',

//remove it

if( $piece.hasClass('selected') ) {

$piece.removeClass('selected');

}

//if $piece does not have the class 'selected'

//make sure no other divs with the class 'piece'

//have that class, then set $piece to have the class

else {

$('div.piece').removeClass('selected');

$piece.addClass('selected');

}

}

function incrementMoveCount() {

moveCount = parseInt($('span#moveCount').html(),10);

moveCount++;

$('span#moveCount').html(moveCount);

}

Checkers.html <html>

<head>

<title>Checkers</title>

<link rel="stylesheet" href="style.css"/>

<script src='script.js'></script>

<script src='provided.js'></script>

</head>

<body>

<div id="game">

<div id="board">

</div>

<div id="pieces">

</div>

</div>

<div id="meta">

<h1>Checkers</h1>

<h4>Moves: <span id="moveCount">0</span></h4>

</div>

</body>

</html>

Style.css

div#game {

position:relative;

}

div#board {

float:left;

height:382px;

width:382px;

border-style:solid;

border-width:9px;

border-color:#DEB887;

}

div.square {

float:left;

position:relative;

width:46px;

height:46px;

border-width:2px;

border-right-style:solid;

border-bottom-style:solid;

border-color:#444;

}

div.square.movable:hover {

-webkit-box-shadow: inset 0px 0px 8px #FFD700;

-moz-box-shadow: inset 0px 0px 8px #FFD700;

box-shadow: inset 0px 0px 8px #FFD700;

cursor:pointer;

}

/* the bottom row */

div.square:nth-last-child(-n + 8) {

border-bottom-style:none;

}

/* the sides */

div.square:nth-child(8n) {

border-right-style:none;

}

div.square.light {

background-color:#ccc;

}

div.square.dark {

background-color:#333;

}

div#pieces {

position:absolute;

/* 9 px puts us inside of the board's borders;*/

left:9px;

top:9px;

background-color:green;

}

div.piece {

position:absolute;

width:32px;

height:32px;

margin:7px;

-webkit-box-shadow: 0px 0px 3px #666;

-moz-box-shadow: 0px 0px 3px #666;

box-shadow: 0px 0px 3px #666;

-webkit-border-radius:16px;

-moz-border-radius:16px;

border-radius:16px;

background-color:blue;

}

div.piece:hover {

-webkit-box-shadow: 0px 0px 8px #FFD700;

-moz-box-shadow: 0px 0px 8px #FFD700;

box-shadow: 0px 0px 8px #FFD700;

cursor:pointer;

}

div.piece.selected {

-webkit-box-shadow: 0px 0px 8px #FFD700;

-moz-box-shadow: 0px 0px 8px #FFD700;

box-shadow: 0px 0px 8px #FFD700;

}

div.piece.light {

background-color:red;

}

div.piece.dark {

background-color:blue;

}

div#meta {

float:right;

}

Provided.js

//global variables for one square

var width = 46;

var border = 2;

//utility function for translating an x,y coordinate

//to a pixel position

//the convention is that the square in the upper left

//corner is at position 0,0

//the square in the upper right, at 7,0 and the lower

//right at 7,7

function getPixels(x,y) {

//ok... so takes an x,y position, returns

//pixels from the left, right

return {

'top': (y * (width+border))+'px',

'left': (x * (width+border))+'px'

};

}

//utility function for turning a pixel position

//into the x,y coordinate of a square on the board

//it follows the same coordinate convention as getPixels

function getCoords(top,left) {

//returns an x and a y

//given a top and left pixels

return {

'x': left / (width + border),

'y': top / (width + border)

};

}

//utility function for returning

//the set of unoccupied dark squares

//(possible places to move a checker piece)

function getMovableSquares() {

//select all of the squares

var $squares = $('div.square');

//select the occupied ones using the jQuery map() method

//map creates a new object from an existing one

//using a translation function

var $takenSquares =

$('div.piece').map(function(index,piece) {

//this function translates a piece

var position = $(piece).position();

var coords = getCoords(position.top,position.left);

var squareIndex = coords.y * 8 + coords.x;

return $squares[squareIndex];

});

var $out = $('div.square.dark').not($takenSquares);

return $out;

}

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

//Creating the 64 squares and adding them to the DOM

var squareCount = 8*8;

for (var i = 0;i<squareCount;i++) {

//this line creates a new div with the class 'square'

//and appends it to the div with id 'board'

$('div#board').append($('<div/>').addClass('square'));

}

//YOUR CODE

//set up the board with the correct classes

//for the light and dark squares

setUpBoard();

//creating the 24 pieces and adding them to the DOM

var pieceCount = 24;

for (var i=0;i<pieceCount;i++) {

//this line appends an empty div

//with the class 'piece' to the div with id 'pieces'

$('div#pieces').append($('<div/>').addClass('piece'));

}

//YOUR CODE

//sets up the classes for the different types of piece

setUpPieces();

//this loop moves all the light pieces to their initial positions

$('div.piece.light').each(function(index,piece) {

//turning the index (from 0 - 11)

//into a x,y square coordinate using math

var y = Math.floor(index / 4);

var x = (index % 4) * 2 + (1 - y%2);

//turning the x,y coordingate into a pixel position

var pixelPosition = getPixels(x,y);

//YOUR CODE

//actually moving the piece to its initial position

movePieceTo($(piece),pixelPosition.top,pixelPosition.left);

});

//this loop moves all the dark pieces to their initial positions

$('div.piece.dark').each(function(index,piece) {

//turning the index (from 0 - 11)

//into a x,y square coordinate using math

var y = Math.floor(index/4) + 5;

var x = (index % 4) * 2 + (1-y%2);

//turning the x,y coordinate into a pixel position

var pixelPosition = getPixels(x,y);

//YOUR CODE

//moving the piece to its initial position

movePieceTo($(piece),pixelPosition.top,pixelPosition.left);

});

//set up initial squares

//the class 'movable' represents a square

//that is unoccupied

getMovableSquares().addClass('movable');

//and now the events

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

//turn `this` into a jQuery object

var $this = $(this);

//YOUR CODE

//toggleing the 'selected' class of this piece

//and possible deselecting other pieces

toggleSelect($this);

});

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

//turn `this` into a jQuery object

var $this = $(this);

//if $this is a legal square to move to...

if ($this.hasClass('movable')) {

//get the piece with the class 'selected'

var $selectedPiece = $('div.piece.selected');

//we only move if there is exactly one selected piece

if ($selectedPiece.length == 1) {

//get the index of the square

//and translate it to pixel position

var index = $this.prevAll().length;

var x = index % 8;

var y = Math.floor(index / 8);

var pixels = getPixels(x,y);

//YOUR CODE

//actually do the moving

movePieceTo($selectedPiece,pixels.top,pixels.left);

//YOUR CODE

//increment the move counter

incrementMoveCount();

//un-select the piece

$selectedPiece.removeClass('selected');

//set the new legal moves

$('div.square').removeClass('movable');

getMovableSquares().addClass('movable');

}

}

});

});

_____________________________________________________________________________________

$ и $()

var jQuery = $; - функция, возвращает объект.

var jQueryObject = $(); - объект

$ methods and attributes

  • fn

  • extend

  • noConflict

  • isReady

  • readyWait

  • holdReady

  • ready

  • bindReady

  • isFunction

  • isArray

  • isWindow

  • isNumeric

  • type

  • isPlainObject

  • isEmptyObject

  • error

  • parseJSON

  • parseXML

  • noop

  • globalEval

  • camelCase

  • nodeName

  • each

  • trim

  • makeArray

  • inArray

  • merge

  • grep

  • map

  • guid

  • proxy

  • access

  • now

  • uaMatch

  • sub

  • browser

  • Callbacks

  • Deferred

  • when

  • support

  • cache

  • uuid

  • expando

  • noData

  • hasData

  • data

  • removeData

  • _data

  • acceptData

  • _mark

  • _unmark

  • queue

  • dequeue

  • valHooks

  • attrFn

  • attr

  • removeAttr

  • attrHooks

  • propFix

  • prop

  • propHooks

  • event

  • removeEvent

  • Event

  • find

  • expr

  • unique

  • text

  • isXMLDoc

  • contains

  • filter

  • dir

  • nth

  • sibling

  • buildFragment

  • fragments

  • clone

  • clean

  • cleanData

  • cssHooks

  • cssNumber

  • cssProps

  • style

  • css

  • swap

  • curCSS

  • get

  • post

  • getScript

  • getJSON

  • ajaxSetup

  • ajaxSettings

  • ajaxPrefilter

  • ajaxTransport

  • ajax

  • param

  • active

  • lastModified

  • etag

  • speed

  • easing

  • timers

  • fx

  • offset

  • boxModel

  • boxModel

$() methods and attributes

  • constructor

  • init

  • selector

  • jquery

  • length

  • size

  • toArray

  • get

  • pushStack

  • each

  • ready

  • eq

  • first

  • last

  • slice

  • map

  • end

  • push

  • sort

  • splice

  • extend

  • data

  • removeData

  • queue

  • dequeue

  • delay

  • clearQueue

  • promise

  • attr

  • removeAttr

  • prop

  • removeProp

  • addClass

  • removeClass

  • toggleClass

  • hasClass

  • val

  • on

  • one

  • off

  • bind

  • unbind

  • live

  • die

  • delegate

  • undelegate

  • trigger

  • triggerHandler

  • toggle

  • hover

  • blur

  • focus

  • focusin

  • focusout

  • load

  • resize

  • scroll

  • unload

  • click

  • dblclick

  • mousedown

  • mouseup

  • mousemove

  • mouseover

  • mouseout

  • mouseenter

  • mouseleave

  • change

  • select

  • submit

  • keydown

  • keypress

  • keyup

  • error

  • contextmenu

  • find

  • has

  • not

  • filter

  • is

  • closest

  • index

  • add

  • andSelf

  • parent

  • parents

  • parentsUntil

  • next

  • prev

  • nextAll

  • prevAll

  • nextUntil

  • prevUntil

  • siblings

  • children

  • contents

  • text

  • wrapAll

  • wrapInner

  • wrap

  • unwrap

  • append

  • prepend

  • before

  • after

  • remove

  • empty

  • clone

  • html

  • replaceWith

  • detach

  • domManip

  • appendTo

  • prependTo

  • insertBefore

  • insertAfter

  • replaceAll

  • css

  • serialize

  • serializeArray

  • ajaxStart

  • ajaxStop

  • ajaxComplete

  • ajaxError

  • ajaxSuccess

  • ajaxSend

  • show

  • hide

  • _toggle

  • fadeTo

  • animate

  • stop

  • slideDown

  • slideUp

  • slideToggle

  • fadeIn

  • fadeOut

  • fadeToggle

  • offset

  • position

  • offsetParent

  • scrollLeft

  • scrollTop

  • innerHeight

  • outerHeight

  • height

  • innerWidth

  • outerWidth

  • width

_____________________________________________________________________________________

$.isArray

$.isArray() is a method that will return true if the object passed to it is an array, and false otherwise. It is very useful because the pure JavaScript typeof keyword will return the same value for both arrays and objects.

function safeLength(object) {

if ($.isArray(object)){

return object.length;

}

else {

return 0;

}

}

_____________________________________________________________________________________

.map()

Pass each element in the current matched set through a function, producing a new jQuery object containing the return values.

The .map() method is particularly useful for getting or setting the value of a collection of elements.

function alertTheEachMes() {

//use $() to select all the divs with class 'eachMe'

var $allOfTheEachMeDivs = $('div.eachMe');

//keeper for our alerts

var capturedAlerts = $.map($allOfTheEachMeDivs,function(value)

{

return $(value).html();

});

return capturedAlerts;

}

_____________________________________________________________________________________

.data( key, value )

Key A string naming the piece of data to set.

Value The new data value; it can be any Javascript type including Array or Object.

Store arbitrary data associated with the matched elements.

With two arguments, it sets the second argument to the key of the first. With one argument, it gets the value stored at the given key.

$('body').data('foo', 52);

$('body').data('bar', { myType: 'test', count: 40 });

$('body').data('foo'); // 52

$('body').data(); // {foo: 52, bar: { myType: 'test', count: 40 }}

$element.data('key') returns the value stored at key.

$element.data('key',value) stores the given value at key.

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

//get the div.

//do not add var before this object for testing purposes!!

$datafulDiv = $('#dataful');

//get the value stored at 'x'

$datafulDiv.data('x');

//double it and store it at 'y'. again do not use var!

$datafulDiv.data('y',$datafulDiv.data('x')*2);

});

_____________________________________________________________________________________

.attr()

  • Метод attr(name) получает значение заданного атрибута соответствующего элемента набора jQuery, либо первого элемента в наборе jQuery (если их несколько). Возвращает значение undefined, если у элемента указанный атрибут отсутствует или в наборе нет элементов.

Возвращаемое значение: (строка) Значение искомого атрибута или undefined.

Параметры:

  • name – (строка) Имя атрибута, значение которого необходимо получить.

  •  Примечание:

  • Чтобы получить значения атрибутов для каждого элемента в наборе jQuery, можно использовать методы .each() или .map().

  •  Примечание:

  • Удалить атрибут средствами jQuery можно с помощью функции .removeAttr().

  • var title = $("img").attr("alt") + " -> Увеличить";

  • $("img:first").attr("title", title);

  • $newDiv.attr('id','new-div');

Iterate over all of the <a> elements on the page, setting each 'href' attribute to "/life" + its current value. For example, "/pictures" would become "/life/pictures".

$(document).ready(function(){

//use $() to select all the 'a' elements

var $allTheLinks = $('a');

//iterate over each one, using attr()

//to alter the 'href' attribute as described

$allTheLinks.each(function(){

var temp = $(this).attr('href');

$(this).attr('href',"/life" + temp);

});

});

_____________________________________________________________________________________

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