3
제 첫 번째 jquery 플러그인입니다. 꽤 끝나지 않았지만 문제가 있습니다.Jquery - 내 첫 번째 플러그인 - 데이터를 저장할 수 없습니다.
이 기능의 일반적인 목적은 선택 상자를 가져 와서 divs 등으로 구성된 더보기 좋은 것을 만드는 동안 그것을 숨기는 것입니다. 예를 들어, 당신은 할 수 있습니다
<select class="beautify" id="items" name="select2" >
<option value="opt1">Select A Brand</option>
<option value="opt2">Option 2</option>
<option value="opt3">Option 3</option>
<option value="opt4">Option 4</option>
<option value="opt5">Option 5</option>
<option value="opt6">Option 6</option>
<option value="opt7">Option 7</option>
<option value="opt8">Option 8</option>
</select>
그런 다음 나중에 호출 할 수
$('select.beautify').beautify();
그래서 내가 작업 및 애니메이션의 대부분을 가지고있다. 각 옵션의 값을 각 앵커에 저장하는 방법을 파악하려고합니다. data() 함수가 제대로 작동하지 않습니다. 각 옵션의 값을 앵커에 저장해야하며 앵커를 클릭하면 선택 값을 해당 값으로 변경해야합니다.
여기에 플러그인입니다 :이 플러그인은 매우 완료되지
(function($){
$.fn.beautify = function() {
var defaults = {
suffix: 'beautify'
};
var options = $.extend(defaults, options);
return this.each(function() {
$(this).hide();
var selectbox = $(this);
var suffix = options.suffix;
var id = $(this).attr('id');
var mainElement = '';
var headElement = id + 'head' + suffix;
var choicesElement = id + 'choices' + suffix;
// Build up the main element container
mainElement += '<div id="';
mainElement += id + suffix;
mainElement += '">';
mainElement += '</div';
$(this).before(mainElement);
// Add the head and choices sections
$('#' + id + suffix).append('<div id="' + headElement + '"></div>');
$('#' + id + suffix).append('<div id="' + choicesElement + '"></div>');
// Take care of some styling
$('#' + id + suffix).addClass('selectouter');
$('#' + headElement).addClass('');
$('#' + choicesElement).addClass('selectchoices');
// Get the choices from the input dropdown
$('#' + headElement).append($(this).children(':first').text());
$(this).find('option').each(function(){
$('#' + choicesElement).append('<a href="#">'+$(this).text()+'</a>');
$('#' + choicesElement).slideDown();
$('#' + choicesElement + ':last-child').data('testvar', $(this).val());
});
// Handle animations
$('#' + choicesElement).hide();
$('#' + headElement).click(function(){
$('#' + choicesElement).slideToggle();
});
$('#' + id + suffix).mouseleave(function(){
$('#' + choicesElement).slideUp();
});
// A new option has been clicked
$('#' + choicesElement + ' a').click(function(event){
event.preventDefault();
$('#' + choicesElement).slideToggle();
$('#' + headElement).html($(this).text());
// Up to now, it's all for looks, actually switch the select value here:
alert($(this).data('testvar'));
});
});
};
})(jQuery);
에도 불구하고, 나는 또한 비판을 감사하겠습니다.
문제가 너무 많아 현재 디버깅하기가 어려워 지므로 도움이 될 것입니다. – balupton
비평 요구 이후;) 현명하게 변수 선택 상자에 $ (this)를 지정하지만 플러그인 전체에 $ (this)를 사용하십시오. 대신 캐시 된 선택 상자 참조를 사용하지 않는 이유는 무엇입니까? 그러면 select 요소 당 약 8 건의 jQuery() 함수가 저장됩니다. 거대하지는 않지만 한 페이지에 여러 개의 선택 항목이있는 경우 차이가 날 수 있습니다. 그리고 IMHO, $ (this)보다 selectbox를 사용하면 작동하는 것이 명확합니다. –