随着web2.0到来,Ajax,RSS的火热,js越来越多的被使用,jQuery是一个强大的js框架,他能令我们写更少的代码,越来越少,啦啦啦啦,越来越少,啦啦啦啦。
让我来边学边写,耶!
1.先看这个
$(document).ready(function() { $("a").click(function() { alert("Hello world!"); }); });
$(document).ready(function() 就是传说中的onload,$("a")是获取所有a标签,就是链接标签:) .click(function(){})是为所有连接标签加上一个onclick方法,这个方法干什么?就是alert("Hello world!");
2.再看这个
$(document).ready(function() { $("#orderedlist").addClass("red"); });
$("#orderedlist")是获取id为orderelist的element(请允许我这样称呼),
.addClass("red");给这个element加上一个css:("red")
3.继续来看
$(document).ready(function() { $("#orderedlist > li").addClass("blue"); });
$(document).ready(function() { $("#orderedlist li:last").addClass("blue"); });
$("#orderedlist > li") 获取id为orderelist的element下的所有的<li>标签。
$("#orderedlist li:last")获取id为orderelist的element下的最后一个<li>标签
4.不要停
$(document).ready(function() { $("#orderedlist").find("li").each(function(i) { $(this).html( $(this).html() + " BAM! " + i ); }); });
$("#orderedlist").find("li")就等于$("#orderedlist li")
.each()迭代了所有的li,并可以在此基础上作更多的处理。
.html()是获取对象的html代码 .html("xxx")是设置"xxx"为对象的html代码
5.继续啊
$(document).ready(function() { $("li").not("[ul]").css("border", "1px solid black"); });
$("li").not("[ul]")是选择所有li,除去有ul子元素的li元素
"[ ]"是用来表示一个元素的子元素或者属性
$(document).ready(function() { $("a[@href*=/content/gallery]").background("#eee"); });
$("a[@href*=/content/gallery]")是选择href为/content/gallery的连接,要注意的是,"*="是部分匹配,而"="是完全匹配,不能乱搞!
6.来点高级的
$(document).ready(function() { $('#faq').find('dd').hide().end().find('dt').click(function() { var answer = $(this).next(); if (answer.is(':visible')) { answer.slideUp(); } else { answer.slideDown(); } }); });
$('#faq').find('dd').hide().end()选择id为faq的元素,找他名为dd的子元素并隐藏,之后结束这次find,并进行下一次find,找到dt元素,给他加上click事件。
.next();是取得一个匹配的元素集合中每一个元素紧邻的后面同辈元素的元素集合。
.is()用一个表达式来检查当前选择的元素集合,如果其中至少有一个元素符合这个给定的表达式就返回true,如果没有元素符合这个表达式,或者表达式是无效的,都返回false。
hide(),show(),隐藏/显示匹配元素。
slideToffle(),slideUp(),slideDown()通过高度变化使匹配的元素以“滑动”的方式隐藏或显示。
fadeTo(),fadeIn(),fadeOut(),通过不透明度的变化来实现所有匹配元素的淡入淡出效果。
7.还不够劲?
$(document).ready(function() { $("a").hover(function() { $(this).parents("p").addClass("highlight"); }, function() { $(this).parents("p").removeClass("highlight"); }); });
parent(),parents(),children(),next(),prev()等等等等.......
8.累了,下次再来!