javascript - How to rewrite the code using jQuery -


how rewrite code using jquery?

 <script type="text/javascript">     window.onload = function(){         var array = document.getelementsbytagname('div');         (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 want alert index:

example: http://jsfiddle.net/ksyr6/

   // wrapping code in anonymous function passed parameter    //    jquery ensure not run until dom ready.    // shortcut jquery's .ready() method $(function() {     $('div').each(function( ) {          $(this).click(function() {             alert( );          });      }); }); 

this finds elements tag name 'div', , iterates on them, individually assigning click event alerts index.

or if index not important, becomes simpler:

example: http://jsfiddle.net/ksyr6/1/

$(function() {     $('div').click(function() {          // have access element received event via "this"          // alert(this.id) alert id of element clicked         alert( 'i clicked' );      }); }); 

here same iteration taking place, implicit. jquery iterates on 'div' elements, giving each on click event handler fires alert.

this nice feature of jquery. pass css selector, finds matching elements, , iterates on them automatically, firing whatever method call.


Comments

Popular posts from this blog

c++ - Convert big endian to little endian when reading from a binary file -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

unicode - Are email addresses allowed to contain non-alphanumeric characters? -