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>
&开发者_开发知识库lt;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.
I won't rewrite it for you, but some pointers:
- jQuery's equivalent for
document.getElementsByTagName
is thejQuery
function (usually aliased as$
unless you usenoConflict
). jQuery's version accepts virtually all of CSS3's selectors (and then some). - jQuery's equivalent of
window.onload
is theload
event onwindow
, which you can hook via.load
, but you probably want to look atjQuery.ready
for a better alternative. - You can bind a
click
handler using the.click
function. - You can loop through all matching elements in the result from #1 above with
.each
.
It's well worth taking a couple of hours and reading through the jQuery API documentation. There are also (at a guess) approximately 157,342 books available on it (which will obviously take a bit longer to read). ;-) Doing that reading will save you a lot of time in the long run, even if it seems to slow you down at first. Have fun!
jQuery(function(){
jQuery('div').bind('click',function(){
alert('alert');
})
});
.
$(function(){
$('div').each(function(i){
$(this).click(function(){
alert(i);
})
});
});
jQuery('document').ready(function(){ jQuery('div').click(function(){ alert(jQuery(this).html()); }); });
精彩评论