Nov 29, 2010

jQuery

'abc' + 3 -> 'abc3'

jQuery is a small 24k (minified) JavaScript library, provides an extremely easy and powerful selectors to select almost anything you want in HTML page. In addition, it also comes with many innovative ways for DOM traversing, event handling (form, browser, mouse ,keyboard), animations effects and Ajax to simplifies the web development. It will definitely change the way you code JavaScript.

最好的 Tutorial:
jQuery Fundamentals
最好的参考
jQuery API

本文分两部分。第二部分内容为 jquery ajax。

jQuery 基础

在jQuery中,最重要的是 jQuery 对象。A jQuery object contains a collection of Document Object Model (DOM) elements that have been created from an HTML string or selected from a document.
注意:element 对应 html 的 tag. CSS 和其他 attributes 不是elements.

jQuery 还是一个函数(可以认为构造函数?),调用它返回一个 jQuery 对象。
1. jQuery 函数接受如下参数:


  • jQuery( selector [, context] )

    selectorA string containing a selector expression,CSS selectors
    contextA DOM Element, Document, or jQuery to use as context,缩小查找范围,默认是 document
    $('div.foo');
    $('div.foo').click(function() {
      $('span', this).addClass('bar');
    });
  • version added: 1.0jQuery( element )

    elementA DOM element to wrap in a jQuery object.
    $('div.foo').click(function() {
      $(this).slideUp();
    });
  • version added: 1.0jQuery( object )

    objectA plain object to wrap in a jQuery object.
  • version added: 1.0jQuery( elementArray )

    elementArrayAn array containing a set of DOM elements to wrap in a jQuery object.
  • version added: 1.0jQuery( jQuery object )

    jQuery objectAn existing jQuery object to clone.
  • version added: 1.4jQuery()


In jQuery, this almost always refers to the raw DOM element on which the function is currently operating. So, in the case of .each(), it refers to the current element in the set of elements we're iterating over.

更多例子:


// create a jQuery object from a DOM element
$( document.body.children[0] );

// create a jQuery object from a list of DOM elements
$( [ window, document ] );

// make a selection in the context of a DOM element
var firstBodyChild = document.body.children[0];
$( 'li', firstBodyChild );

// make a selection within a previous selection
var paragraph = $( 'p' );
$( 'a', paragraph );

2. jQuery 函数还可以直接接受 html,返回对象


  • jQuery( html [, ownerDocument] )

    htmlA string of HTML to create on the fly. Note that this parses HTML, not XML.
    ownerDocumentA document in which the new elements will be created
  • version added: 1.4jQuery( html, props )

    htmlA string defining a single, standalone, HTML element (e.g.
    or
    ).
    propsAn map of attributes, events, and methods to call on the newly-created element.
3. jQuery 函数最后还有一个用途,相当于 $(document).ready()

 jQuery 函数(函数也是对象)有自己的 properties 和 methods
 jQuery.ajax
 jQuery.support

$ 是什么?

Javascript 中 $ 不是特殊字符,可以用在变量和函数命名。在 jquery 中,$有特殊的含义:

// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;

  1. 它相当于 jQuery 函数。
  2. 它相当于 $(document).ready()
  3. 所以看到 $.ajax 也不要惊慌

建议:如果用变量来保存选择结果,变量名建议以 $ 开头 var $divs = $('div');


$(document).ready()

 the page is in a state where it's ready to be manipulated. 

$( document ).ready(function() {
  console.log( 'ready!' );
});

$(function() {
  console.log( 'ready!' );
});

Selector

选择时,selector 最好有一点特定性,这样会提高 jquery 效率。

选择的结果是元素列表,可能包含零个元素,单个元素,或者多个元素
因为 javascript 中空列表 [] 是 true,故不能用 if( $() ) 来判断是否有选择结果,正确方法是
if($('div.foo').length ) {
 // some code
}

$() 函数支持大多数 css3 selectors,个别 pseudo selector 或许有含义的不同

Getting single elements from a selection

  1. 采用 index 方式返回 raw DOM element
  2. 采用 eq() 方式返回 jQuery 对象
var listItems = $( 'li' );
var rawElement = listItems[0];
var html = rawElement.innerHTML;

var secondListItem = listItems.eq( 0 );
var html2 = secondListItem.html();

有了Selection能干什么?


  • 对selected DOM elements进行操作
  • 绑定selected DOM elements的事件 handler
  • 让 selected DOM elements 显示特效(Animation effects)
但别急。先进一步 refine selection

 selection test, filter, DOM traversing, chaining, adding

jquery 对象是dom elements的collection,
.is() 
Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.
  • .is( selector )

    selectorA string containing a selector expression to match elements against.
  • version added: 1.6.is( function(index) )

    function(index)A function used as a test for the set of elements. It accepts one argument, index, which is the element's index in the jQuery collection.Within the function, this refers to the current DOM element.
  • version added: 1.6.is( jQuery object )

    jQuery objectAn existing jQuery object to match the current set of elements against.
  • version added: 1.6.is( element )

    elementAn element to match the current set of elements against.
$("ul").click(function(event) {
  var $target = $(event.target);
  if ( $target.is("li") ) {
    $target.css("background-color", "red");
  }
});

filter

很多情况下你不会想对整个 collection进行操作。先进行filter
和 is 不同,filter 返回 jQuery object。is 返回 true/false

var listItems = $( 'li' );

// filter the selection to only items with a class of 'special'
var special = listItems.filter( '.special' );

// filter the selection to only items without a class of 'special'
var notSpecial = listItems.not( '.special' );

// filter the selection to only items that contain a span
var hasSpans = listItems.has( 'span' );

DOM traversal

// get the first list item on the page
var listItem = $( 'li' ).first(); // also: .last()

// get the siblings of the list item
var siblings = listItem.siblings();

// get the next sibling of the list item
var nextSibling = listItem.next(); // also: .prev()

// get the list item's parent
var list = listItem.parent();

// get the list items that are immediate children of the list
var listItems = list.children();

// get ALL list items in the list, including nested ones 包含 descendants
var allListItems = list.find( 'li' );

// find all ancestors of the list item that have a class of "module"
var modules = listItem.parents( '.module' );  包含 ancestors

// find the closest ancestor of the list item that has a class of "module"
var module = listItem.closest( '.module' );

chaining

选择结果还可以采用级联方式进一步 refine,refine 不改变原先选择列表,因此可以通过 $.fn.end 返回原列表。
$('#content')
    .find('h3')
    .eq(2)
        .html('new text for the third h3!')
    .end() // restores the selection to all h3's in #content
    .eq(0)
        .html('new text for the first h3!');
end() 返回原列表,可以用两个 end 返回原原列表
$('div#link').find('a')
                .eq(0)
                .css( 'color', '#50981b' )
                .end() //返回 find('a')
                .css({'font-size':'20px'})
                .end() //返回 $('div#link')
                .css({'border':'1px solid'});

往 selection 里添加,end(), addback()

.add() method. You can pass it a selector, an array of elements, a string of HTML, or a jQuery object.

end(), addback() 主要用于 chaining。但 chainning 要谨慎使用,因为它使得代码不要阅读。
参见这儿

说完了 selection,先说对selection DOM elements的操作

操作分为 setter, getter, element 操作(place, copy, remove)
  • Adding and removing classes: addClass(), removeClass()
  • Changing style: css('key','value') 或者 css({'key':'value','key':'value'})
  • Changing form values: val(), prop(),参见下面说明
  • Changing other attributes: attr('key','value'), removeAttr()
  • 直接修改 html
  • Getting information from elements: 和上面几项相同名字的 getter. 除此以外,还有 html(), text()
  • Placing elements in the document: appendTo() append() insertAfter(). place around inside outside
  • Copying elements: .clone() clone->manipulate->place 
  • Removing elements。有三种方法 remove, detach, replacewith,从字面可以理解。remove会丢掉event handler,detach则保留event handler。replacewith也会丢掉event handler
prop 类似 attr
getter .prop( propertyName )
setter .prop( propertyName, value )
目前理解是,其他 attribute 使用 .attr,而 checked attribute 要使用 .prop()
  • getter,返回第一个元素的性质(除了 text()函数,该函数返回全部)
  • setter,设置所有元素的性质
When manipulation methods are used as getters, the method operates on only the first element in the selection, with one notable exception: the .text() method. In the case of the .text() method, the text of all selected elements will be returned if no argument is passed to the method.

getter, setter 名字相同
html('code') 为 setteing
html() 为 getter

html() 返回当前 element tag 内包含的 html,不包括当前element 的 tag
<a href="#">link 1 <em>So important. </em></a>
$('a').html() ->   link 1 <em>So important. </em>
$('a').text()  ->   link 1 So important.


setter 操作是对整个 selection进行的,所以又叫 implicit iteration

explicit iteration
Sometimes, the task you're trying to accomplish won't fit neatly into one of jQuery's existing methods, and you'll need to explicitly iterate over a selection. The .each() method lets you do this.
$( 'li' ).each(function( index, elem ) {
  // this: the current, raw DOM element
  // index: the current element's index in the selection
  // elem: the current, raw DOM element (same as this)
  $( elem ).prepend( '' + index + ': ' );
});

setter 操作的value参数可以为函数,该函数有两个参数(index, old_value),返回 new value
$( 'a' ).attr( 'href', function(index, value) {
  return value + '?special=true';
});


jquery 的选择、选择 refine、setter 函数都返回相同类型的 jquery 对象,因此可以进行级联。
getter 返回第一个元素的的性质,不能级联。

Example 3.18: Getting CSS properties
1$('h1').css('fontSize'); // returns a string such as "19px"
2$('h1').css('font-size'); // also works
Example 3.19: Setting CSS properties
1$('h1').css('fontSize''100px'); // setting an individual property
2$('h1').css({ 'fontSize' '100px''color' 'red' }); // setting multiple properties


1var $h1 = $('h1');
2
3$h1.addClass('big');
4$h1.removeClass('big');
5$h1.toggleClass('big');
6
7if ($h1.hasClass('big')) { ... }

其中 hasClass,只有某个元素有 big,则返回 true。而大括号里面,如果继续调用 $h1,依旧是所有被选择元素,而不是有 big 的元素

是使用 $.fn.css,还是使用 clss?
根据弱耦合原则,推荐使用 class。因为这样具体CSS表现代码可以写在 css 文件中,和 javascript 代码分离。



1$('h1').width('50px');   // sets the width of all H1 elements
2$('h1').width();         // gets the width of the first H1
3
4$('h1').height('50px');  // sets the height of all H1 elements
5$('h1').height();        // gets the height of the first H1
6
7$('h1').position();      // returns an object containing position
8                         // information for the first H1 relative to
9                         // its "offset (positioned) parent"

Example 3.22: Setting attributes
1$('a').attr('href''allMyHrefsAreTheSameNow.html');
2$('a').attr({
3    'title' 'all titles are the same too!',
4    'href' 'somethingNew.html'
5});

说完操作,接下来说事件

Native Event NameShorthand Method
click.click()
keydown.keydown()
keypress.keypress()
keyup.keyup()
mouseover.mouseover()
mouseout.mouseout()
mouseenter.mouseenter()
mouseleave.mouseleave()
scroll.scroll()
focus.focus()
blur.blur()
resize.resize()


event 对象
$( document ).on( 'click', function( event ) {
  console.log( event.type );    // The event type, eg. "click"
  console.log( event.which );   // The button or key that was pressed.
  console.log( event.target );  // The originating element. DOM element 的 html
  console.log( event.pageX );   // The document mouse X coordinate.
  console.log( event.pageY );   // The document mouse Y coordinate.
});



以下 'event' 指表格左列名字

//注册一个 event handler
$('li').on('event', function(event){ do something; });
由于 this 代表 selected dom element,因此在 event handler 中
直接使用 this 或者使用 $(this),后者是一个 jquery object


亦可用
var handleClick = function() {
  console.log( 'something was clicked' );
};
$( 'li' ).on( 'click', handleClick );
下同

//对同一个事件注册两个 handlers。好像执行顺序是按照注册的前后
$('li').on('event.subname1', function(event){ do something; });
$('li').on('event.subname1', function(event){ do something else; });

// 注册两个事件
$('li').on('event1 event2', function(event){ do something; }); // 注册两个事件

//注销event handler
$('li').off('event')
$('li').off('event.subname')

//手动触发 event,而非用户通过 UI 触发
$('li').trigger('event')
$('li').trigger('event.subname')

上述没有用到表格右边的 shorthand name
$('li').click(function(event){ do something; }); //绑定
$('li').click(); //触发

禁止默认行为

Often, you'll want to prevent the default action of an event; for example, you may want to handle a click on an a element using AJAX, rather than triggering a full page reload. Many developers achieve this by having the event handler return false, but this actually has another side effect: it stops the propagation of the event as well, which can have unintended consequences. The right way to prevent the default behavior of an event is to call the .preventDefault() method of the event object.


$( 'a' ).on( 'click', function( event ) {
  // Prevent the default action.
  event.preventDefault();
  // Log stuff.
  console.log( 'I was just clicked!' );
});

Event bubbling and event delegation

待添加

Selected elements 特效



  • .show() Show the selected elements.
  • .hide() Hide the selected elements.
  • .fadeIn() Animate the opacity of the selected elements to 100%.
  • .fadeOut() Animate the opacity of the selected elements to 0%.
  • .slideDown() Display the selected elements with a vertical sliding motion.
  • .slideUp() Hide the selected elements with a vertical sliding motion.
  • .slideToggle() Show or hide the selected elements with a vertical sliding motion, depending on whether the elements are currently visible.

自定义动画

The .animate() method takes up to three arguments:
  • an object defining the properties to be animated
  • the duration of the animation, in milliseconds
  • a callback function that will be called when the animation is complete

管理动画

  • .stop() will stop currently running animations on the selected elements.
  • .delay() will pause before the execution of the next animation method. Pass it the number of milliseconds you want to wait.


javascript 的 bind 和 jquery 的 bind:
javascript 的 bind:
fun2 = fun1.bind(object)
将函数 fun1 绑定于对象 object,输出函数 fun2

jquery 的 bind
$.fn.bind(Event,fun)
将 $选择的元素的Event时间,绑定于响应函数 fun


Effect:
成对

$.fn.show
$.fn.hide

$.fn.fadeIn
$.fn.fadeOut

$.fn.slideDown
$.fn.slideUp

$.fn.slideToggle
用户自己定义的Effect
$.fn.animate
1$('div.funtimes').animate(
2    {
3        left : "+=50",
4        opacity : 0.25
5    },
6    300, // duration
7    function() { console.log('done!'); // calback
8});



其他参考:
jQuery Tutorials

jQuery – Attribute selector examples

0 comments: