首页 > jquery > jquery中each操作用法例子

jquery中each操作用法例子

each(callback)
以每一个匹配的元素作为上下文来执行一个函数。
意味着,每次执行传递进来的函数时,函数中的this关键字都指向一个不同的DOM元素(每次都是一个不同的匹配元素)。而且,在每次执行函数时,都会给函数传递一个表示作为执行环境的元素在匹配的元素集合中所处位置的数字值作为参数(从零开始的整形)。 返回 'false' 将停止循环 (就像在普通的循环中使用 'break')。返回 'true' 跳至下一个循环(就像在普通的循环中使用'continue')。

主要需要掌握的是 $("div").each(function(index, domEle) {//index, domEle
%@ Page Language="C#" AutoEventWireup="true" CodeBehind="jqueryeach.aspx.cs" Inherits="tsz.jqueryeach" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
      <script src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.js" type="text/javascript"></script>
      <script>
          $(document).ready(function() {
              $("button").click(function() {
                  $("div").each(function(index, domEle) {//index=i 循环变量比如这里指的是第i个div, domEle=this  此处 this 指代的是 DOM 对象而非 jQuery 对象。
                      // domEle == this
                      $(domEle).css("backgroundColor", "yellow");
                      if ($(this).is("#stop")) {
                          $("span").text("Stopped at div index #" + index);
                        
                          return false;
                      }
                  });
              });
          });
      </script>
</head>
<body>
    <form id="form1" runat="server">
    <button>Change colors</button>
<span></span>
<div></div>
<div></div>

<div></div>
<div></div>
<div id="stop">Stop here</div>
<div></div>

<div></div>
<div></div>
     </form>
</body>
</html>

原创文章转载请注明出处:云飞扬IT的blog

本文链接: http://www.ajaxcn.net/archives/641

分类: jquery 标签:
一键分享到:新浪微博分享  分享到网易微博    转贴到开心网  推荐到豆瓣  分享到QQ空间    RSS订阅
  1. 本文目前尚无任何评论.
  1. 本文目前尚无任何 trackbacks 和 pingbacks.