我之前得到了一些关于选择器的帮助,但我坚持以下几点。
假设你有一个这样的插件
$('#box').customplugin();
如何在插件中将#box作为字符串获取?我不确定这是否是正确的方法,任何其他的解决方案也是很好的。
考虑到#box是一个选择下拉列表,
我遇到的问题是,如果我使用常规的javascript
$('#box').val(x);
选择正确的选项值,
但是如果我在一个插件中尝试同样的方法
.....
this.each(function() {
var $this = $(this);
$this.val(x);
最后一段代码实际上并没有做任何事情。
我注意到我在定位插件中的#box时遇到了问题,因为它是一个对象而不是一个字符串……
任何帮助都将不胜感激。
谢谢!
编辑::为了更好地理解我正在工作的代码
(function($){
$.fn.customSelect = function(options) {
var defaults = {
myClass : 'mySelect'
};
var settings = $.extend({}, defaults, options);
this.each(function() {
// Var
var $this = $(this);
var thisOpts = $('option',$this);
var thisSelected = $this[0].selectedIndex;
var options_clone = '';
$this.hide();
options_clone += '<li rel=""><span>'+thisOpts[thisSelected].text+'</span><ul>'
for (var index in thisOpts) {
//Check to see if option has any text, and that the value is not undefined
if(thisOpts[index].text && thisOpts[index].value != undefined) {
options_clone += '<li rel="' + thisOpts[index].value + '"><span>' + thisOpts[index].text + '</span></li>'
}
}
options_clone += '</ul></li>';
var mySelect = $('<ul class="' + settings.myClass + '">').html(options_clone); //Insert Clone Options into Container UL
$this.after(mySelect); //Insert Clone after Original
var selectWidth = $this.next('ul').find('ul').outerWidth(); //Get width of dropdown before hiding
$this.next('ul').find('ul').hide(); //Hide dropdown portion
$this.next('ul').css('width',selectWidth);
//on click, show dropdown
$this.next('ul').find('span').first().click(function(){
$this.next('ul').find('ul').toggle();
});
//on click, change top value, select hidden form, close dropdown
$this.next('ul').find('ul span').click(function(){
$(this).closest('ul').children().removeClass('selected');
$(this).parent().addClass("selected");
selection = $(this).parent().attr('rel');
selectedText = $(this).text();
$(this).closest('ul').prev().html(selectedText);
$this.val(selection); //This is what i can't get to work
$(this).closest('ul').hide();
});
});
// returns the jQuery object to allow for chainability.
return this;
}
https://stackoverflow.com/questions/5477394
复制相似问题