链式编程
1、原理:return this;
2、通常情况下,只有设置操作才能把链式编程延续下去。因为获取操作的时候,会返回获取到的相应的值,无法返回 this。
3、end():结束当前链最近的一次过滤操作,并且返回匹配元素之前的状态。
<!DOCTYPE html><html lang="en"><head> ???<meta charset="UTF-8"> ???<title>Title</title> ???<script src="jquery-1.11.1.js"></script> ???<style> ???????ul { ???????????list-style: none; ???????} ???????li { ???????????width: 50px; ???????????background-color: #cccccc; ???????????margin: 10px; ???????} ???</style> ???<script> ???????$(function () { ???????????$("button").click(function () { ???????????????//end()会过滤一次返回$("li").eq(3)的对象 ???????????????$("li").eq(3).css("height", 50).prevAll().css("height", 100).end().css("backgroundColor", "red"); ???????????}); ???????}); ???</script></head><body><button>end()</button><ul> ???<li>0</li> ???<li>1</li> ???<li>2</li> ???<li>3</li> ???<li>4</li> ???<li>5</li></ul></body></html>
隐式迭代
1、含义:方法的内部会为匹配到的所有元素进行循环遍历,执行相应的方法;而不用我们再进行循环,简化我们的操作,方便我们调用。如果获取的是多元素的值,大部分情况下返回的是第一个元素的值
2、优点:jQuery这一特性相比较js而言,在注册事件上很方便,无需循环注册事件
3、each():函数遍历;虽然有隐式迭代,但是对每个元素做不同的处理,这时候就用到了each方法
//参数一表示当前元素在所有匹配元素中的索引号//参数二表示当前元素(DOM对象)//element是一个js对象,需要转换成jquery对象$(selector).each(function(index,element){});
<!DOCTYPE html><html lang="en"><head> ???<meta charset="UTF-8"> ???<title>Title</title> ???<script src="jquery-1.11.1.js"></script> ???<style> ???????span { ???????????font-size: 50px; ???????????cursor: pointer; ???????} ???</style> ???<script> ???????$(function () { ???????????//点到谁 谁就会变成实心的 ???????????// ???????????$("span").mouseenter(function () { ???????????????$(this).text("★").prevAll().text("★").end().nextAll().text("☆"); ???????????}); ???????????$("div").mouseleave(function () { ???????????????$("span").each(function (index, ele) { ???????????????????if ($(ele).attr("lighted") == 1) { ???????????????????????$(ele).text("★"); ???????????????????} else { ???????????????????????$(ele).text("☆"); ???????????????????} ???????????????}); ???????????}); ???????????$("span").click(function () { ???????????????$(this).attr("lighted", 1); ???????????????$(this).prevAll().attr("lighted", 1); ???????????????$(this).nextAll().attr("lighted", 0); ???????????}); ???????}); ???</script></head><body><div> ???<span>☆</span> ???<span>☆</span> ???<span>☆</span> ???<span>☆</span> ???<span>☆</span></div></body></html>
jQuery——链式编程与隐式迭代
原文地址:http://www.cnblogs.com/wuqiuxue/p/8040291.html