How to rewrite the code using jQuery?
<script type="text/javascript">
window.onload = function(){
var array = document.getElementsByTagName('div');
for (var i=0; i<array.length; i++) {
(function(i) {
array[i].onclick = function() {
alert(i);
}
})(i);
}
};
</script>
<div>0</div>
<div>1</div>
Thanks...
If you actually want to alert the index:
Example: http://jsfiddle.net/Ksyr6/
// Wrapping your code in an anonymous function that is passed as a parameter
// to jQuery will ensure that it will not run until the DOM is ready.
// This is a shortcut for jQuery's .ready() method
$(function() {
$('div').each(function( i ) {
$(this).click(function() {
alert( i );
});
});
});
This finds all elements with the tag name 'div'
, and iterates over them, individually assigning a click event that alerts its index.
Or if the index is not important, it becomes simpler:
Example: http://jsfiddle.net/Ksyr6/1/
$(function() {
$('div').click(function() {
// You have access to the element that received the event via "this"
// alert(this.id) will alert the ID of the element that was clicked
alert( 'i was clicked' );
});
});
Here the same iteration is taking place, but it is implicit. jQuery iterates over the 'div'
elements, giving each on the click event handler that fires an alert.
This is a nice feature of jQuery. You pass it a CSS selector, it finds matching elements, and iterates over them automatically, firing whatever method you call.