2013-02-27 3 views
0

텍스트 상자에 대해 다중 열 드롭 다운을 만들 수있는 간단한 플러그인을 개발했습니다. 웹 서비스 URL과 결과 집합의 각 열에서 채울 각 요소에 해당하는 jQuery 선택기 배열을 전달합니다.jQuery 플러그인 및 변수 범위

$ ('#의 txtProduct') multiColumnDropDown. ({ 'URL' '/ API/GetProductAndCategoryByRegion' '타겟': '#txtProduct' '#txtCategory "] });

이렇게하면 다중 열 드롭 다운이 생성되고 사용자가 해당 열의 레코드를 클릭하면 #txtProduct 및 #txtCategory가 채워집니다.

모든 것이 제대로 작동하지만 내 페이지에 여러 개의 멀티 열 드롭 다운을 적용 할 수 있기를 원합니다. 플러그인 인스턴스에 따라 동적으로 생성 된 드롭 다운 마크 업을 참조하는 방법을 모르겠다는 점에서 문제가 발생할 것입니다.

내 플러그 인에서 드롭 다운의 래퍼를 생성하고 필요한 위치에 배치합니다. 재 쿼리를 통해 래퍼와 해당 드롭 다운을 업데이트하려는 경우 생성 된 모든 래퍼가 아니라 원하는대로 업데이트하는 방법은 무엇입니까? 아래

전체 코드 :

(function ($) { 
var methods = { 
    init: function (options) { 
     return this.each(function() { 
      var settings = $.extend({ 
       'targets': [this] 
      }, options); 

      var targets = settings["targets"]; 

      var yOffset = $(this).position().top + $(this).height() + 'px'; 
      var xOffset = $(this).position().left + 'px'; 

      var wrapper = $('<div class="dropdown-wrapper"></div>') 
       .css('top', yOffset) 
       .css('left', xOffset) 
       .hide(); 

      $(document).click(function() { 
       wrapper.hide(); 
      }) 

      if (settings["url"] != undefined && settings["url"] != '') { 
       methods.populateDropDown(settings["url"], targets, wrapper); 
      } 

      $(this).click(function (e) { 
       e.stopPropagation(); 
       wrapper.show(); 
      }); 
     }); 
    }, 
    update: function (options) { 
     return this.each(function() { 
      var settings = $.extend({ 
       'targets': [this] 
      }, options); 

      var targets = settings["targets"]; 

      //How do I reference the correct wrapper? 
      //The following will reference all wrappers on the page :\ 
      var wrapper = $('div.dropdown-wrapper') 

      //Repopulate the wrapper and dropdown code goes here.... 
     }) 
    }, 
    populateDropDown: function (url, targets, wrapper) { 
     $.ajax({ 
      url: url, 
      type: 'get', 
      dataType: 'json' 
     }) 
     .done(function (data) { 
      var $table = $('<table class="multi-column-table">'); 
      data.forEach(function (item) { 
       var $tr = $('<tr>').appendTo($table); 
       var idx = 0; 
       $.each(item, function (k, v) { 
        var $td = $('<td>'); 
        if (targets[idx] != undefined) 
         $td.attr('data-target', targets[idx]); 
        $td.text(v); 
        $td.appendTo($tr); 
        idx++; 
       }); 
      }); 
      $table.on('click', 'tr', function() { 
       $.each(this.children, function (i, td) { 
        if ($(td).attr('data-target')) 
         $($(td).attr('data-target')).val($(td).text()); 
       }); 
      }); 
      $(wrapper).append($table).prependTo('body'); 

     }) 
     .fail(function (jqXHR, textStatus, errorThrown) { 
      alert('Error: ' + errorThrown); 
     }); 
    } 
}; 

$.fn.multiColumnDropDown = function (method) { 
    if (methods[method]) { 
     return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); 
    } else if (typeof method === 'object' || !method) { 
     return methods.init.apply(this, arguments); 
    } else { 
     $.error('Method ' + method + ' does not exist on jQuery.multiColumnDropDown'); 
    } 
}; 

}) (jQuery를);

그리고 경우 중 하나는 CSS에 관심이 :

.dropdown-wrapper 
{ 
border:1px solid #000; 
border-bottom-right-radius:3px; 
border-bottom-left-radius:3px; 
z-index:100; 
background-color:#fff; 
position:absolute; 
} 

.dropdown-wrapper tr:hover 
{ 
background-color:#0081C2; 
color:#fff; 
} 

답변

0
당신은이 안내서를 참조 할 수 있습니다

JQuery와 플러그인 제작은 (http://docs.jquery.com/Plugins/Authoring)

는 기본적으로, 당신이 플러그인의 인스턴스를 저장해야 html 컨트롤의 데이터 속성 당신이 눈치처럼 당신이 dropdown-wrapper 클래스와 모든 div의를 선택하고 있기 때문에, 페이지에서 update 방법 참조 내 모든 래퍼를

var $this = $(this), 
     data = $this.data('tooltip'), 
     tooltip = $('<div />', { 
      text : $this.attr('title') 
     }); 

    // If the plugin hasn't been initialized yet 
    if (! data) { 

     /* 
     Do more setup stuff here 
     */ 

     $(this).data('tooltip', { 
      target : $this, 
      tooltip : tooltip 
     }); 
+0

강타에, 나는 가이드에서 그 부분을 놓쳤음에 틀림 없었다. 고마워! –

0

var wrapper = $('div.dropdown-wrapper') 아래의 코드를 확인하십시오.

해당 인스턴스에서 작성된 랩퍼를 참조하려면 init 함수에서 작성된 랩퍼를 어 @ 곳에 저장해야합니다. 이를 위해 플러그인 컨텍스트에서 data 메서드를 사용할 수 있습니다.