jQuery中$.each()函数的用法引申实例
网络编程 2021-07-04 21:04www.168986.cn编程入门
jQuery中的$.each()函数比forEach更加强大,可以用来遍历JavaScript中的任意集合,借来下来我们会举几个jQuery中$.each()函数的用法引申实例,首先先来回顾一下遍历用法的基础:
语法:
$.each( collection, callback(indexInArray, valueOfElement) )
值得一提的是,forEach 可以很方便的遍历数组和 NodeList ,jQuery 中的 jQuery 对象本身已经部署了这类遍历方法,而在原生 JavaScript 中则可以使用 forEach 方法,但是 IE 并不支持,因此我们可以手动把 forEach 方法部署到数组和 NodeList 中:
if ( !Array.prototype.forEach ){ Array.prototype.forEach = function(fn, scope) { for( var i = 0, len = this.length; i < len; ++i) { fn.call(scope, this[i], i, this); } } } // 部署完毕后 IE 也可以使用 forEach 了 document.getElementsByTagName('p').forEach(function(e){ e.className = 'inner'; });
而jQuery中的$.each()函数则更加强大。$.each()函数和$(selector).each()不一样。$.each()函数可以用来遍历任何一个集合,不管是一个JavaScript对象或者是一个数组,如果是一个数组的话,回调函数每次传递一个数组的下标和这个下标所对应的数组的值(这个值也可以在函数体中通过this关键字获取,但是JavaScript通常会把this这个值当作一个对象即使他只是一个简单的字符串或者是一个数字),这个函数返回所遍历的对象,也就是这个函数的第一个参数,注意这里还是原来的那个数组,这是和map的区别。
其中collection代表目标数组,callback代表回调函数(自己定义),回调函数的参数第一个是数组的下标,第二个是数组的元素。当然我们也可以给回调函数只设定一个参数,这个参数一定是下标,而没有参数也是可以的。
例1:传入数组
<!DOCTYPE html> <html> <head> <script src=”http://code.jquery./jquery-latest.js”></script> </head> <body> <script> $.each([52, 97], function(index, value) { alert(index + ‘: ‘ + value); }); </script> </body> </html>
输出:
0: 52 1: 97
例2:如果一个映射作为集合使用,回调函数每次传入一个键-值对
<!DOCTYPE html> <html> <head> <script src=”http://code.jquery./jquery-latest.js”></script> </head> <body> <script> var map = { ‘flammable': ‘inflammable', ‘duh': ‘no duh' }; $.each(map, function(key, value) { alert(key + ‘: ‘ + value); }); </script> </body> </html>
输出:
flammable: inflammable duh: no duh
例3:回调函数中 return false时可以退出$.each(), 如果返回一个非false 即会像在for循环中使用continue 一样, 会立即进入下一个遍历
<!DOCTYPE html> <html> <head> <style> div { color:blue; } div#five { color:red; } </style> <script src=”http://code.jquery./jquery-latest.js”></script> </head> <body> <div id=”one”></div> <div id=”two”></div> <div id=”three”></div> <div id=”four”></div> <div id=”five”></div> <script> var arr = [ "one", "two", "three", "four", "five" ];//数组 var obj = { one:1, two:2, three:3, four:4, five:5 }; // 对象 jQuery.each(arr, function() { // this 指定值 $(“#” + this).text(“Mine is ” + this + “.”); // this指向为数组的值, 如one, two return (this != “three”); // 如果this = three 则退出遍历 }); jQuery.each(obj, function(i, val) { // i 指向键, val指定值 $(“#” + i).append(document.createTextNode(” – ” + val)); }); </script> </body> </html>
输出 :
Mine is one. – 1 Mine is two. – 2 Mine is three. – 3 - 4 - 5
编程语言
- 机械手焊接机器人编程 机械手焊接设备编程
- vb数据库编程实例,vb做数据库
- tiobe世界编程语言排行榜,全球编程语言排行
- 成都java编程培训 成都it编程培训中心
- 编程基础培训,编程基础知识培训
- flash游戏编程基础教程,flash游戏开发教程
- 不会英语能学编程吗 不会英语可以学程序员吗
- 爱心代码编程C语言 爱心代码编程c语言公式
- c语言编程学习入门 c语言编程快速入门
- 西门子plc编程培训 西门子plc编程培训班
- 哪里可以学编程 台州哪里可以学编程
- 少儿编程哪个好 少儿编程哪个品牌好
- 编程是什么意思,图形编程是什么意思
- c语言编程软件下载,c语言编程软件在哪下载
- java编程软件下载,java编程下载手机版
- ug编程培训学校,ug编程培训教程