views:

117

answers:

5

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

A: 
jQuery(function(){
     jQuery('div').bind('click',function(){
            alert('alert');
     })
});
Praveen Prasad
What happened to `i`?
David Dorward
A: 
jQuery('document').ready(function(){

jQuery('div').click(function(){

alert(jQuery(this).html());

});




});
sushil bharwani
What happened to `i`?
David Dorward
Very good design as well!
Algorithm
the innerHTML of DIVS is containing 1,2,3 etc so i did alert the innerHTML
sushil bharwani
a -1 to a "very good design comment" by author. I just didnt understand whats wrong with code.
sushil bharwani
A: 

.

$(function(){
  $('div').each(function(i){
    $(this).click(function(){
      alert(i);
    })
  });
});
Sarfraz
+4  A: 

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.

patrick dw
Thanks for your answers
Algorithm
The `$(function(){})` is a method that adds an event listener on the page that executes its contents on DOM ready.
BrunoLM
why the each....?
Caspar Kleijne
@Caspar - OP wanted to `alert()` the index number of each element. This is not available from a typical `$('div').click(...` without calling `.index()` inside the handler. It is much quicker to use the index number made available by `.each()`.
patrick dw
+2  A: 

I won't rewrite it for you, but some pointers:

  1. jQuery's equivalent for document.getElementsByTagName is the jQuery function (usually aliased as $ unless you use noConflict). jQuery's version accepts virtually all of CSS3's selectors (and then some).
  2. jQuery's equivalent of window.onload is the load event on window, which you can hook via .load, but you probably want to look at jQuery.ready for a better alternative.
  3. You can bind a click handler using the .click function.
  4. 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!

T.J. Crowder
T.J. - With regard to your *"Off-topic"*, the example code passes `i` into a self calling function. As such, the `onclick` will reference its local version of `i`, which will persist until (and after) the event occurs. Example: http://jsfiddle.net/Ksyr6/2/
patrick dw
I know Javascript very well, but I don't know jQuery. So I'll learn the one/
Algorithm
@patrick dw: Thanks for pointing that out, I totally missed that he was passing it through a function and so the `i` being alerted was not the `i` in the outer loop. Should have read more carefully. Thanks again.
T.J. Crowder
@Algorithm: Then you'll have no problem picking up jQuery. Just give the API docs a read and have at it.
T.J. Crowder