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/
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/
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.