Wednesday, October 01, 2008

jQuery Object Accessors example


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript" charset="utf-8" src="/lib/jquery/jquery-1.2.6.js"></script>
<style type="text/css" media="screen">
p {
margin: 3px;
}
.first {
color: #f90;
}
.second {
color: #f00;
min-height: 20px;
border: #949 1px solid;
margin: 5px 0px;
}
.three {
font-size: 18px;
color: blue;
border: blue 1px solid;
cursor: pointer;
}
</style>
</head>
<body>
<div id="d1">div#d1</div>
<div class="first">div.first</div>
<div class="first">div.first</div>
<div class="first">div.first</div>
<p>one</p> <div><p>two</p></div> <p>three</p>
Reversed - <div id="reversed"></div>
To do list: <span class="three">click here to change</span>
<span></span>
<ul>
<li>Eat</li>
<li>Sleep</li>
<li>Play</li>
<li>Be merry</li>
</ul>
<button>Change colors</button>
<span>this span innerText will be changed.</span>
<div class="second"></div>
<div class="second"></div>
<div class="second"></div>
<div class="second"></div>
<div class="second"></div>
<div class="second" id="stop">colors change will stop here</div>
<div class="second"></div>
<div class="second"></div>
<div class="second"></div>
<div class="second"></div>

<input type="checkbox" name="t1" value="test1" id="t1"/>checkbox#t1

<script type="text/javascript" charset="utf-8">
$("span.three").click(function () {
// console.log(arguments);
$("li").each(function(){
$(this).toggleClass("first");
});
});
$("button").click(function () {
$("div.second").each(function (index, domEle) {
// this == domEle, $(this) == jQuery Object
$(domEle).css("backgroundColor", "yellow");
if ($(this).is("#stop")) {
$("span").not(".three").text("Stopped at div index #" + index);
return false; // break loop
}
});
});
$("#reversed").html($("p").get().reverse().map(function(elem){
return elem.innerHTML;
}).join(','));
$("p").eq(2).text("four");
$("span, ul, li", document.body).click(function (e) {
e.stopPropagation();
var domEl = $(this).get(0);
$("span:first").text("Clicked on - " + domEl.tagName);
});
$("div").click(function () {
// this is the dom element clicked
var index = $("div").index(this);
$("span:last").text("That was div index #" + index);
});
$(document.body).click(function () {
// because span/ul/li has stopPropagation event, div will not be added.
$(document.body).append($("<div>"));
var n = $("div").length;
$("span:eq(1)").text("There are " + n + " divs." +
"Click to add more.");
}).trigger('click'); // trigger the click to start
</script>
</body>
</html>

No comments :