2009-07-23 2 views
2

첫 번째 jquery 플러그인을 만들려고합니다. 기본적으로 마우스 오버/클릭 상태 등으로 div에서 버튼을 만듭니다. 다음 코드는 기본 버튼에서 작동하지만 강조 방법을 만들고 싶습니다. '보통'클래스를 대체 할 클래스를 지정하십시오. 메서드를 호출하지만 옵션을 읽을 수없는 것 같아? 또한 클래스 이름 (addClass)을 하드 코딩하여 할당 한 경우 마우스 오버 및 클릭 상태에서 마우스 이벤트가 손실되는 것 같습니다.jquery 플러그인 사용자 정의 메서드

코드 : 나는 당신이 달성하려고하는 무엇인지 정확히 모르겠어요

(function(jQuery) { 
jQuery.fn.divbutton = function(options) 
    { 
     // default settings 
     var options = jQuery.extend(
     { 
      width: '75px',         // button width 
      height: '25px',         // button height 
      normal_class: 'brighterbutton',     // normal state class 
      highlight_class: 'brighterbutton-highlight', // normal state class 
      mouseover_class: 'brighterbutton-mouseover', // mouseover class 
      mousedown_class: 'brighterbutton-mousedown', // mousedown class 
      highlighted: false 
     }, 
     options); 
    this.each(function() 
    { 
     jQuery(this).addClass(options.normal_class); 
     jQuery(this).width(options.width); 
     jQuery(this).height(options.height); 

     jQuery(this).mouseover(function() { 
      jQuery(this).addClass(options.mouseover_class); 
     }); 

     jQuery(this).mouseout(function() { 
      jQuery(this).removeClass(options.mouseover_class); 
      jQuery(this).removeClass(options.mousedown_class); 
     }); 

     jQuery(this).mousedown(function() { 
      jQuery(this).addClass(options.mousedown_class); 
     }); 

     jQuery(this).mouseup(function() { 
      jQuery(this).removeClass(options.mousedown_class); 
     }); 
    }); 

    // public methods 
    this.doHighlight = function() 
    { 
     alert("this doesnt get called"); 
     return this; 
    }; 

    return this; 
}; 



jQuery.fn.highlight = function() 
{ 
    alert("this gets called"); 

    return this.each(function() 
    { 
     //this.removeClass(this.options.normal_class); 
     //this.addClass(this.options.highlight_class); 
    }); 
}; 

})(jQuery); 
+4

여러 번 jQuery (this)를 사용하지 마십시오. var에 저장하십시오. var $ this = $ (this); – redsquare

+0

이것은 좋은 팁입니다, 감사합니다 –

+0

죄송합니다 ...하지만 그 차이점은 무엇입니까? 타이핑 할 문자는 거의 없습니까? – Fernando

답변

1

도움을 주신 모든 분들께 감사 드리며, 내가 시작한 작업을 처리했습니다. 즉, CSS 클래스를 통해 모든 모양과 느낌이 완전히 설정된 "강조 표시 가능한"버튼이 있어야합니다. 내 jquery에 대한 나의 제한된 지식을 기반으로하고 chaining 방법이 더 빠르고 더 효율적일 것이라는 확신이 없기 때문에 이것의 효율성을 질문한다.

;(function(jQuery) { 
    jQuery.fn.brighterbutton = function(options) { 
     // default settings 
     var options = jQuery.extend(
     { 
      width: '75px',            // button width 
      height: '25px',            // button height 
      normal_class: 'brighterbutton',        // normal state class 
     mouseover_class: 'brighterbutton-mouseover',    // mouseover class 
     mousedown_class: 'brighterbutton-mousedown',    // mousedown class 
     highlight_class: 'brighterbutton-highlight',    // highlight class 
     highlight_mouseover: 'brighterbutton-highlight-mouseover' // highlight mouseover class 
    }, 
    options || {}); 

    this.each(function() { 
     var self = jQuery(this); 

     self.addClass(options.normal_class); 
     self.width(options.width); 
     self.height(options.height); 

     self.mouseover(function() { 
      self.addClass(options.mouseover_class); 
     }); 

     self.mouseout(function() { 
      self.removeClass(options.mouseover_class); 
      self.removeClass(options.mousedown_class); 
     }); 

     self.mousedown(function() { 
      self.addClass(options.mousedown_class); 
     }); 

     self.mouseup(function() { 
      self.removeClass(options.mousedown_class); 
     }); 
    }); 

    jQuery.fn.highlight = function() { 
     var self = jQuery(this); 
     return self.each(function() { 
      self.addClass(options.highlight_class); 

      self.unbind('mouseover').mouseover(function() { 
       self.addClass(options.highlight_mouseover); 
       self.removeClass(options.highlight_class); 
      }); 

      self.unbind('mouseout').mouseout(function() { 
       self.removeClass(options.mouseover_class); 
       self.removeClass(options.mousedown_class); 
       self.removeClass(options.highlight_mouseover); 
       self.addClass(options.highlight_class); 
      }); 

      self.unbind('mousedown').mousedown(function() { 
       self.removeClass(options.mouseover_class); 
       self.removeClass(options.highlight_mouseover); 
       self.addClass(options.mousedown_class); 
      }); 

      self.unbind('mouseup').mouseup(function() { 
       self.removeClass(options.mousedown_class); 
      }); 

     }); 
    }; 

    return this; 
}; 
})(jQuery); 
5

- 당신이 목적 doHighlight()이 될 것입니다 무엇에 정교한 수 있을까?

외부 플러그인을 사용할 때만 내부 플러그인을 사용할 수 있도록 $.fn을 다른 플러그인 내부로 확장 할 수 있습니다. 예를 들어,

Working Demo - 코드를 데모

.brighterbutton { background-color: yellow; } 
.brighterbutton-highlight { background-color: red; } 
.brighterbutton-mouseover { background-color: orange; } 
.brighterbutton-mousedown { background-color: purple; } 

과 코드에 사용

CSS 색상을 볼 수있는 URL에 /편집를 추가

(function($) { 

     $.fn.divbutton = function(options) 
      { 
       // default settings 
       var settings = $.extend(
       { 
        width: '75px',         // button width 
        height: '25px',         // button height 
        normal_class: 'brighterbutton',     // normal state class 
        highlight_class: 'brighterbutton-highlight', // normal state class 
        mouseover_class: 'brighterbutton-mouseover', // mouseover class 
        mousedown_class: 'brighterbutton-mousedown', // mousedown class 
        highlighted: false 
       }, 
       options||{}); 
      this.each(function() 
      { 
       var $this = $(this); 

       $this.addClass(settings.normal_class); 
       $this.width(settings.width); 
       $this.height(settings.height); 

       $this.mouseover(function() { 
        $this.addClass(settings.mouseover_class); 
        $this.doHighlight(); // call inner plugin 
       }); 

       $this.mouseout(function() { 
        $this.removeClass(settings.mouseover_class); 
        $this.removeClass(settings.mousedown_class); 
       }); 

       $this.mousedown(function() { 
        $this.addClass(settings.mousedown_class); 
       }); 

       $this.mouseup(function() { 
        $this.removeClass(settings.mousedown_class); 
       }); 
      }); 

      // inner plugin that can be used only when 
      // divbutton plugin has been used 
      $.fn.doHighlight = function() 
      { 
       $this.addClass(settings.highlight_class); 
      }; 

      return this; 
     }; 

    })(jQuery); 

I don't know whether this is good practice. The inner plugin does have access to the outer plugin's settings object however. 

편집 :

여기 당신이 그것을 처리 할 수있는 하나의 방법입니다 -이 의견

(function($) { 
$.fn.divbutton = function(options) 
    { 
     // default settings 
     options = $.extend(
     { 
      // it might be easier to pass an object 
      // to jQuery's css command 
      css: {   width : '75px',    
          height: '25px', 
          'text-align': 'center' 
       },        
      standardClass: 'brighterbutton',    
      saveClass:  'brighterbutton-highlight', 
      overClass:  'brighterbutton-mouseover', 
      downClass:  'brighterbutton-mousedown', 
      saveButton: false 
     }, 
     options||{}); 

     // if a saveButton is wanted, then use the save CSS class 
     // which can still be supplied in the options 
     if(options.saveButton) 
      options.standardClass = options.saveClass; 

    this.each(function() 
    { 
     var $this = $(this); 

     $this.addClass(options.standardClass); 
     $this.css(options.css); 

     $this.mouseover(function() { 
      $this.addClass(options.overClass); 
     }); 

     $this.mouseout(function() { 
      $this.removeClass(options.overClass); 
      $this.removeClass(options.downClass); 
     }); 

     $this.mousedown(function() { 
      $this.addClass(options.downClass); 
     }); 

     $this.mouseup(function() { 
      $this.removeClass(options.downClass); 
     }); 
    }); 
    return this; 
}; 
})(jQuery); 

Working Demo

jQuery 코드

$(function() { 
    $('div.standard').divbutton(); 
    $('div.save').divbutton({ saveButton: true }); 
}); 

HTML

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> 
<head> 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> 
<title>Sandbox</title> 
<meta http-equiv="Content-type" content="text/html; charset=utf-8" /> 

<style type="text/css" media="screen"> 

    body { background-color: #fff; font: 16px Helvetica, Arial; color: #000; } 
    .brighterbutton { background-color: yellow; } 
    .brighterbutton-highlight { background-color: red; } 
    .brighterbutton-mouseover { background-color: orange; } 
    .brighterbutton-mousedown { background-color: purple; } 

</style> 
</head> 
    <body> 
    <div style="margin:100px;"> 
     <p>A standard button</p> 
     <div class="standard">Standard</div> 
    </div> 
    <div style="margin:100px;"> 
     <p>A save Button</p> 
     <div class="save">Save</div> 
    </div> 
    </body> 
</html> 
의 동화입니다
+0

안녕하십니까, 답장을 보내 주셔서 감사합니다. 강조 표시의 목적은 애플리케이션의 양식에 버튼 저장을 강조 표시하는 것입니다. 본질적으로 "normal_class"를 "highlight_class"로 대체하려고합니다. doHighlight 메서드 (아래 코드)에 다음 코드를 추가하면 버튼이 새로운 클래스를 사용하지만 위쪽/아래쪽 마우스 이벤트는 작동하지 않습니다. jQuery (this) .removeClass (options.normal_class); jQuery (this) .addClass (options.highlight_class); 답장을 보내 주셔서 감사합니다. 설정 및 doHighlight 변경 사항은 –

+0

입니다. saveButton을 나타 내기 위해 options 객체에 대한 속성을 가질 수 있습니다. 기본값은 false 일 수 있지만 true가 전달되면 다른 CSS 클래스가 사용됩니다 for normal_class –

+0

안녕하세요, 저는 방금 강조 표시 방법에 전달 된 options.highlighted를 추가했습니다. 모든 단추가이 선택권을보고 그 (것)들은 모두 변화하는 것을 보인다? 이러한 플러그인 옵션 (예 :이 경우 버튼의 모든 인스턴스)이 있습니까? 여전히 jQuery에 대한 내 머리를 얻으려고 노력하고 있습니다. –

관련 문제