为了账号安全,请及时绑定邮箱和手机立即绑定

jQuery实战读书笔记

标签:
JQuery

第一章 jQuery 基础

1. 包装器

jQuery对包装器(Wrapper)或包装集(wrapped set)进行操作,即 $(selector)或jQuery(selector)这样的结构。

jQuery选择器完整列表:http://docs.jquery.com/Selectors。

2.实用函数

如:var trimmed = $.trim(someString); 或 var trimmed = jQuery.trim(someString);

3. 文档就绪处理程序

$(document).ready(function(){ });

简写形式:$(function(){ });

4. 创建DOM元素

$("

Hi there!

").insertAfter("#followMe");


5. 扩展

$.fn.disable = function() {...}

6. 与其他库共存

jQuery.noConflict();

 

第二章 选择元素

$(selector)

$(selector, "div#sampleDOM")

1. 基本CSS选择器

a

#specialID

.specialClass

a#specialID.specialClass

p a.specialClass

合并多个选择器:$("div,span")

2. 子节点、容器和特性选择器

*

E

E F

E>F

E+F

E~F

E.C

E#I

E[A]

E[A=V]

E[A^=V]

E[A$=V]

E[A!=V]

E[A*=V] 包含

3. 位置过滤

:first

:last

:first-child

:last-child

:only-child

:nth-child(n) 从 1 开始计数

:nth-child(even|odd)

:nth-child(Xn+Y)

:even

:odd

:eq(n)

:gt(n)

:lt(n)

示例:

table#languages td:first-child

table#languages td:nth-child(1)

li:nth-child(2n)

tbody tr:eq(2) td:eq(2) td:contains('1972') tbody td:nth-child(3):eq(2)

4. CSS和自定义过滤选择器

:animated

:button

:checkbox

:checked

:contains(food)

:disabled

:enabled

:file

:has(selector)

:header  h1~h6

:hidden

:image

:input

:not(selector)

:parent

:password

:radio

:reset

:selected

:submit

:text

:visible

示例:

input:not(:checkbox)

$("img:not([src*='dog'])")

div:has(span)

$("tr:has(img[src$='puppy.png'])")

 

2. 创建HTML

$("<div>") 与 $("<div></div>") 或 $("<div/>") 是等价的。

示例:

$('<img>',

    {

        src: 'images/little.bear.png',

        alt: 'Little Bear',

        title: '...',

        click: function() { alert($(this).attr('title')); }

    })

    .css({

        cursor: 'pointer',

        border: '1px solid black',

        padding: '12px 12px 20px 12px',

        backgroundColor: 'white'

    })

    .appendTo('body');

 

3. 管理包装集

3.1 大小

.length

.size()

示例:

$('a').length

$('a').size()

3.2 获取元素

[index]

.get(index)

示例:

var imgElement = $('img[alt]')[0];

var imgElement = $('img[alt]").get(0);

$($('p').get(23))

获取元素包装集:

eq(index)

first()

last()

获取元素数组

toArray()

示例:var allLabeledButtons = $('label+button').toArray();

获取元素索引

index(element)

示例:var n = $('img').index($('img#findMe')[0];

简写为:var n = $('img').index('img#findMe');

查找元素自己的索引:var n = $('img').index();

3.3 分解包装集

添加元素:add(expression, context)

示例:$('img[alt]').add('img[title]');

$('img[alt]')

    .addClass('thickBorder')

    .add('img[title]')

    .addClass('seeThrough');

排除元素:not(expression)

示例:$('img[title]').not('[title*=puppy]')

$('img').not(function(){return !$(this).hasClass('keepMe');})

过滤元素:filter(expression)

示例:$('td').filter(function(){return this.innerHTML.match(/^\d+$/)})

$('img').addClass('seeThrough').filter('[title*=dog]').addClass('thickBorder')

获取子集:slice(begin, end) end 不包含在子集内,可省略

$('*').slice(0,4);

获取子集:has(test)

$('div').has('img[alt]')

转换包装集:map(callback)

var allIds = $('div').map(function() {

    return this.id == undefined ? null : this.id;

}).get();

遍历:each(iterator)

$('img').each(function(n){

    this.alt = 'This is image[' + n + '] with an id of ' + this.id;

});

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

3.4 使用关系获取包装集

children([selector])

closest([selector])  邻近祖先元素组成的包装集

contents()

next([selector])

nextAll([selector])

nextUntil([selector])

offsetParent()

parent([selector])

parents([selector])

parentsUntil([selector])

prev([selector])

prevAll([selector])

prevUntil([selector])

siblings([selector])

示例:

$(this).closest('div')

$(this).siblings('button[title="Close"]')

3.5 更多处理方式

find(selector)

is(selector)

示例:wrappedSet.find('p cite');

3.6 管理jQuery链

将当前包装集回滚到前一个返回的包装集:end()

示例:

$('img').filter('[title]').hide();

$('img').filter('[title]').hide().end().addClass('anImage');

合并方法链中的前两个包装集:andSelf()

示例:

$('div')

    .addClass('a)

    .find('img')

    .addClass('b')

    .andSelf()

    .addClass('c');

 

第三章 用jQuery为页面添加活力

3.1 访问元素属性

$('*').each(function(n){

    this.id = this.tagName + n;

});

获取特性值:attr(name)

示例:alert($("#myImage").attr("src"));

 

jQuery 的 attr() 方法的规范化访问名称

规范化名称         DOM名称

cellspacing       cellSpacing

class             className

colspan           colSpan

cssFloat          styleFloat(IE), cssFloat(other browsers)

float             同上

for               htmlFor

frameborder       frameBorder

maxlength         maxLength

readonly          readOnly

rowspan           rowSpan

styleFloat        styleFloat(IE), cssFloat(other browsers)

tabindex          tabIndex

usemap            useMap

 

设置特性值:attr(name, value)

$('*').attr('title', function(index, previousValue) {

    return previousValue + ' I am element ' + index +

        ' and my name is ' + (this.id || 'unset');

});

设置多个特性值:attr(attributes)

$('input').attr(

    {value: '', title: 'Please enter a name'}

);

警告:IE不允许修改INPUT元素的name和type特性。

删除特性:removeAttr(name)

 

示例例1:强制在新窗口打开链接

$("a[href^=htt://']").attr("target", "_blank");

示例2:解决双重提交问题

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

    $(":submit", this).attr("disabled", "disabled");

});

取消禁用:$("xxx").removeAttr("disabled");

在元素上存储自定义属性:data(name, value)

从元素读取自定义属性:data(name)

移除自定义属性:removeData(name)

 

3.2 改变元素样式

addClass(names)  names - 单个类名或空格隔开的多个类名

removeClasse(names)

toggleClass(names)

示例:

function swapThem() {

    $("tr").toggleClass("striped");

}

$(function() {

    $("table tr:nth-child(even)").addClass("striped");

    $("table").mouseover(swapThem).mouseout(swapThem);

});

根据条件切换类:toggleClass(names, switch)

hasClass(name)

 

以数组的形式返回特定元素的类名列表:

方法1:$("p:first").attr("className").split(" ");

方法2:

$.fn.getClassNames = function() {

    var name = this.attr("className");

    if (name != null) {

        return name.split(" ");

    } else {

        return [];

    }

};

设置样式:css(name, value)

$("div.expandable").css("width", function(index, currentWidth) {

    return currentWidth + 20;

});

快捷形式:css(properties)

$("<img>",

    {

        src: ...

    })

    .css({

        cursor: 'pointer',

        border: '1px solid black',

        ...

    });

获取样式:css(name);

 

设置宽度和高度:width(value)  height(value)

$("div.myElements").width(500)

等价于:$("div.myElements").css("width", 500)

获取宽度和高度: width()    height()

 

获取元素的位置:offset() position()

滚动控制:scrollLeft()  scrollLeft(value)  scrollTop() scrollTop(value)

 

3.3 设置元素内容

html()

html(content)

text()

text(content)

append(content)

prepend(content)

before(content)

after(content)

appendTo(targets)

prependTo(targets)

insertBefore(targets)

insertAfter(targets)

wrap(wrapper)

wrapAll(wrapper)

wrapInner(wrapper)

unwrap()

remove(selector) 删除包装集中的所有元素

detach(selector) 功能同上,但保留绑定的事件和jQuery数据

empty()

clone(copyHandlers)

replaceWith(content)

replaceAll(selector)

 

3.4 处理表单元素值

表单插件(http://jquery.malsup.com/form/)。

val()

val(value)

val(values)

示例:

$("[name='radioGroup']:checked").val()

var checkboxValues = $("[name='checkboxGroup']:checked").map(

    function(){ return $(this).val(); }

).toArray();

$("input, select").val(["one", "two", "three"]);

 

第四章 事件处理

4.1 浏览器的事件模型

DOM 第0级事件模型

DOM 第2级事件模型

1. 建立事件处理器:addEventListener(eventType, listener, useCapture)

2. 事件传播:捕获阶段(根到目标)和冒泡阶段(目标到根)

 

4.2 jQuery 事件模型

绑定事件:bind(eventType, data, handler)  bind(eventMap)

$("img").bind("click" function(event){alert("Hi there!");});

<script>

$(function(){

    $("#example")

        .bind("click", function(event) {

            say("BOOM once!");

        })

        .bind("click", function(event) {

            say("BOOM twice!");

        })

        .bind("click", function(event) {

            say("BOOM three times!");

        });

});

</script>

$(".whatever").bind({

  click: function(event){/* handle clicks */},

  mouseenter: function(event){/* handle mouseenters */},

  mouseleave: function(event){/* handle mouseleaves */}

});

 

简化事件绑定:eventTypeName(listener)

支持的事件类型名:blur change click dbclick error focus focusin focusout keydown keypress keyup load mousedown mouseenter mouseleave mousemove mouseout mouseover mouseup ready resize scroll select submit unload

创建一次性事件绑定:one(eventType, data, listener)

删除事件处理器:unbind(eventType, listener)  unbind(eventType)

 

Event实例作为第一个参数传入函数,不管使用什么浏览器。这个Event实例是 jQuery.Event 类型的对象。

属性

altKey

ctrlKey

currentTarget

data

metaKey

pageX

pageY

relatedTarget

screenX

screenY

shiftKey

result

target

timestamp

type

which

方法

preventDefault()

stopPropagation()

stopImmediatePropagation()

isDefaultPrevented()

isPropagationStopped()

isImmediatePropagationStopped()

 

动态管理事件处理器

bind()是静态绑定,在事件触发时只有最先被绑定的元素才会被处理,动态创建的元素不会触发事件。

创建 Live 事件处理    live(eventType, data, listener)

和bind()行为相似,不同之处是,当相应的事件发生时,该方法会为所有匹配选择的元素触发此事件,包括在使用live()方法绑定事件时还不存在的元素。例如:

$("div.attendToMe").live("click", function(event) {

    alert(this);

});

在页面的整个生命周期内,单击任意拥有类 attendToMe 的 DIV 元素都会触发 click 事件,调用绑定的事件处理器。

删除 LIVE 事件处理   die(eventType, listener)

 

触发事件处理器 trigger(eventType, data)

只触发处理器,不需要事件传播和语义动作执行:triggerHandler(eventType, data)

简化的触发事件方法:eventTypeName()

blur change click dblclick error  focus focusin focusout keydown keypress keyup load mousedown mouseenter mouseleave mousemove mouseout mouseover resize scroll select submit unload

 

其他事件相关的方法

toggle(listener1, listener2, ...) 第一次单击调用listener1,第二次单击调用 listener2,……全部执行完后重新开始。

hover(enterHandler, leaveHandler) 第一个是mouseenter事件处理器,第二个是mouseleave处理器

hover(handler) 二合一

 

mouseover 和 mouseout ,鼠标进入某个元素触发 mouseover,移出或进入子元素触发 mouseout。

mouseenter 和 mouseleave,鼠标进入元素触发 mouseenter,移出元素才触发 mouseout。

 

(待续)

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消