Sunday, July 10, 2011

each(callback) → jQuery

This means that every time the passed-in function is executed (which is once for every element matched) the 'this' keyword points to the specific DOM element. Additionally, the function, when executed, is passed a single argument representing the position of the element in the matched set (integer, zero-index). Returning 'false' from within the each function completely stops the loop through all of the elements (this is like using a 'break' with a normal loop). Returning 'true' from within the loop skips to the next iteration (this is like using a 'continue' with a normal loop).

Function callback : The callback to execute for each matched element. <pre>function callback(index, domElement) { this; // this == domElement } </pre>
                                   
Example:
       Iterates over three divs and sets their color property.
    $(document.body).click(function () {
   $("div").each(function (i) {
          if (this.style.color != "blue")
             {
               this.style.color = "blue";
                   }
         else
          {
          this.style.color = "";
           } }); });


<div>Click here</div> 
<div>to iterate through</div> 
<div>these divs.</div>


div { color:red; text-align:center; cursor:pointer; 
font-weight:bolder; width:300px; }


Example:
   If you want to have the jQuery object instead of the regular DOM element, use the $(this) function, for example:
  $("span").click(function () {
    $("li").each(function(){
             $(this).toggleClass("example");
   }); });



To do list: <span>(click here to change)</span>
  <ul>
    <li>Eat</li>
    <li>Sleep</li>

    <li>Be merry</li>
  </ul>

ul { font-size:18px; margin:0; }
  span { color:blue; text-decoration:underline; cursor:pointer; }
  .example { font-style:italic; }

Example:
You can use 'return' to break out of each() loops early.
$("button").click(function () {
$("div").each(function (index, domEle) { // domEle == this $(domEle).css("backgroundColor", "yellow"); if ($(this).is("#stop")) { $("span").text("Stopped at div index #" + index); return false; } }); });

<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 { width:40px; height:40px; margin:5px; float:left;
        border:2px blue solid; text-align:center; }
  span { color:red; }
  <div></div>

No comments:

Post a Comment