HTML and CSS Reference
In-Depth Information
Assume the following HTML makes up the markup for a webpage:
<body>
<table>
<tr>
<td id="door1">Door 1</td>
<td id="door2">Door 2</td>
<td id="door3">Door 3</td>
</tr>
</table>
</body>
The following script is the more traditional method to assign event handlers to the DOM
elements:
<script type=”text/javascript”>
window.onload = function () {
document.getElementById(“door1”).onclick = function () { };
document.getElementById(“door2”).onclick = function () { };
document.getElementById(“door3”).onclick = function () { };
}
This fairly simple script has only three cells to add a click event to. But if the page is to
get more complex and have up to 20 or 50 doors, this code becomes tedious. This is where
jQuery can simplify things. The preceding code can be replaced with this code:
$("document").ready(function () {
$("td").click(function () { });
});
Notice how much easier this code is. In one line, all <td> elements are assigned a click event.
This code applies to all <td> elements on the page. So, if some <td> elements aren't part of the
page, you need to ensure that the selector is unique to the required elements. This can be ac-
complished with cascading style sheets (CSS) or by using the DOM hierarchy, as in this example:
$("document").ready(function () {
$("#GameRow td").click(function () {
alert( $(this).text());
});
});
<table>
<tr id="GameRow">
<td id="door1">Door 1</td>
<td id="door2">Door 2</td>
<td id="door3">Door 3</td>
</tr>
</table>
<table>
<tr id="SomeOtherRow">
<td id="cell1">Not a Door 1</td>
<td id="cell2">Not a Door 2</td>
<td id="cell3">Not a Door 3</td>
</tr>
</table>
Search WWH ::




Custom Search