Head First Jquery学习笔记(二)

本文介绍如何使用jQuery进行DOM操作,包括遍历元素、删除元素、替换元素及插入元素的方法。通过实例演示了climbup、climbdown、climbacross等遍历技巧,并介绍了过滤、切片等选择器的高级应用。

第四章  操作DOM

elements遍历(traverse)、可以删除(remove或者detach)、替换(replacewith)、插入(insert)

1.traverse
dom本身是树结构,可以遍历,有三种操作:
climb up:$(".fish").parent()、$(".fish").parent().parent()
climb down:$(".menu_list").children()
climb across:$(".fish").prev()、$(".fish").next()

查询过滤Use filter methods to narrow your selections
$(".menu_list").children().first();第一个元素
$(".menu_list").children().last();最后一个元素
$(".menu_list").children().eq(0);指定元素索引值

$(".menu_list").children().slice(1,3);指定元素索引值在1和3之间
$(".menu_list").parents().filter(".organic");在参数中指定selector
$("ul.menu_list.organic").children().not(".local");过滤指定selector元素

2.remove or detach
$f = $(".fish").parent().parent().detach();
Putting a dollar sign in front of the variable indicates that it’s storing elements returned from jQuery. 
When we select and detach the li elements and set a variable ($f) to the result, jQuery takes the elements the DOM returns and stores them neatly for us in a JavaScript array. When we want to put those elements back with the restore button, our job will be way less messy.
3.replace
$("h2").replaceWith("<h1>My Menu</h1>");里面可以放HTML代码。
4.insert
向dom中插入内容(Insert HTML content into the DOM)
before inserts content before the selected element.
$(".meat").before("<li>Tofu</li>");
after inserts content after the selected element. 
$(".meat").after("<li>Tofu</li>");

4.数组

jquery数组存储各种东西,包括元素。

$f = $(".fish").parent().parent().detach();返回elements数组,¥标志数据从是jquery东东。
遍历数组用方法each,参数i为元素索引值,this代表当前操作的元素
$(".tofu").each(function(i){
  $(this).after(    );
});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值