简体   繁体   中英

How to know which element was clicked

I have this code:

( function() {
  var i, ii, e = Elements.Select('.drop');
  for ( i = 0, ii = e.length; i < ii; i++ ) {
    e [ i ].onclick = function () {
      alert ( e [ i ].getAttribute('data-open') );
    }
  }
})();

What I do is that when clicking an element with the className 'drop', then alert the attribute of the element I was clicking. But doesn't work's.

this piece of code is the one I use to select an element by her className. Don't pay much attention, its only to show us is just to show them how I select the elements.

(function() {
  Select : function ( element ) { 
  var object, index  = element.substr( 0, 1 ), name = element.substr( 1, element.length ),      clases = [ ], i, all = document.body.getElementsByTagName("*"); 
  switch ( index ) { 
    case '.' : 
      for ( i = 0; i < all.length; i ++ ) { 
        if ( all [ i ].className == name ) {   
          clases.push( all [ i ] ); 
        } 
      } 
      object = clases; 
    break;  
    return object 
    } 
  } 
})();

¿Answers?

( function() {
  var i, ii, e = Elements.Select('.drop');
  for ( i = 0, ii = e.length; i < ii; i++ ) {
    e [ i ].onclick = function () {
      //by the time that this gets executed, the for loop is ended, thus i equals ii
      // instead of using e[i]... try using this : 
      alert (this.getAttribute('data-open'));
      alert ( e [ i ].getAttribute('data-open') );
    }
  }
})();

You can use jquery for this.Here, the 'this' keyword gives you the current element which was clicked. This function is fired on the click event of any element whose class name is 'drop'.

$(".drop").click( function(){
   var x=$(this).attr("data-open");
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM