共享网

JQuery 中each的使用方法
2010-8-20 8:06:55 文章来源: http://www.chr114.com 文章作者: chr114 点击率:
核心提示: JQuery 中each的使用方法
JavaScript代码
  1. JQuery中的each函数在1.3.2的官方文档中的描述如下:   
  2.   
  3. each(callback)    
  4.   
  5. 以每一个匹配的元素作为上下文来执行一个函数。   
  6.   
  7. 意味着,每次执行传递进来的函数时,函数中的this关键字都指向一个不同的DOM元素(每次都是一个不同的匹配元素)。而且,在每次执行函数时,都会给函数传递一个表示作为执行环境的元素在匹配的元素集合中所处位置的数字值作为参数(从零开始的整形)。返回 'false' 将停止循环 (就像在普通的循环中使用 'break')。返回 'true' 跳至下一个循环(就像在普通的循环中使用'continue')。   
  8.   
  9. 而后面的callback 则是回调函数,指示遍历元素的时候应该赋予的操作。先看下面的一个简单的例子:   
  10.   
  11. 迭代两个图像,并设置它们的 src 属性。注意:此处 this 指代的是 DOM 对象而非 jQuery 对象。   
  12.   
  13. HTML 代码:   
  14. <img/><img/>jQuery 代码:   
  15. $("img").each(function(i){   
  16.    this.src = "test" + i + ".jpg";   
  17.  });   
  18.   
  19.     
  20.   
  21.     
  22.   
  23. 结果:[ <img src="test0.jpg" />, <img src="test1.jpg" />  ]当然,在遍历元素的时候,jquery是允许自定义跳出的,请看示例代码:你可以使用 'return' 来提前跳出 each() 循环。   
  24.   
  25. HTML 代码:   
  26. <button>Change colors</button>   
  27. <span></span>    
  28. <div></div>    
  29. <div></div>   
  30.     
  31. <div></div>    
  32. <div></div>   
  33. <div id="stop">Stop here</div>    
  34. <div></div>   
  35.     
  36. <div></div>   
  37. <div></div>   
  38.   
  39.     
  40.   
  41. jQuery 代码:   
  42. $("button").click(function(){   
  43.         $("div").each(function(index,domEle){   
  44.             $(domEle).css("backgroundColor","wheat");   
  45.                if($(this).is("#stop")){   
  46.                  $("span").text("在div块为#"+index+"的地方停止。");   
  47.                  return false;   
  48.                }   
  49.             });   
  50.   
  51.   
  52.     
  53.   
  54.    或者这么写:   
  55.   
  56. $("button").click(function(){   
  57.                $("div").each(function(index){   
  58.                      $(this).css("backgroundColor","wheat");   
  59.                if($(this).is("#stop")){   
  60.                       $("span").text("在div块为#"+index+"的地方停止。");   
  61.                        return false;   
  62.                    }   
  63. });   
  64.   
  65.   
  66.     
  67.   

 

欢迎访问编程之路,请在评论时遵守国家相关法律法规。评论不代表本站观点

  • 访客名称:

2010 编程之路 www.chr114.com All Rights Reserved