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