Example: Implements a simple event delegation: The click handler is added to an unordered list, and the children of its li children are hidden. Clicking one of the li children toggles (see toggle()) their children.
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<ul>
<li>item 1
<ul>
<li>sub item 1-a</li>
<li>sub item 1-b</li>
</ul>
</li>
<li>item 2
<ul>
<li>sub item 2-a</li>
<li>sub item 2-b</li>
</ul>
</li>
</ul>
<script>
function handler(event) {
var $target = $(event.target);
if( $target.is("li") ) {
$target.children().toggle();
}
}
$("ul").click(handler).find("ul").hide();
</script>
</body>
</html>
No comments:
Post a Comment