Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jul 22nd, 2012  |  syntax: None  |  size: 0.76 KB  |  hits: 15  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. how to attach/extend methods to dom element
  2. <div id='hi1'> aaa </div>
  3.        
  4. $('#hi1').sayHi();
  5.        
  6. $.fn.sayHi = function() {
  7.     alert($(this).text());
  8.     return this;
  9. };
  10.  
  11. $('#hi1').sayHi();
  12.        
  13. $.fn.extend({ sayHi:function(){ alert('hi'); });
  14.        
  15. jQuery.fn.sayHi = function() {
  16.   // this is the jQuery object
  17.   // so this[0] is a DOM element (or undefined)
  18. };
  19.        
  20. $.fn.sayHi = function(something){  
  21.     alert(something);      
  22. };
  23.  
  24. $('#hi1').sayHi('hi');    // 'hi' will be passed to the jQuery method 'sayHy'
  25.        
  26. $.fn.sayHi = function(txt, clr){  
  27.      this.css({color: clr}).text(txt); // 'this' is your element delegated to your plugin
  28. };
  29.  
  30. $('#hi1').click(function(){  
  31.     $(this).sayHi('Heading is clicked!', 'red');  // (txt, crl)                                
  32. });