我正在制作一个选择菜单插件,以替换丑陋的默认选择菜单,并在不同操作系统间保持一致。
这是演示(仅限Firefox和Webkit):
http://spacirdesigns.com/selectMenu/
它已经可以工作了,但是我遇到了一个问题,就是无法将 "selected" 属性分配给选项。该代码对于任何其他属性都有效,但我无法让它与 "selected" 属性一起工作。
以下内容有效:
select.find('option')
.removeAttr('whatever')
.eq(index).attr('whatever', 'hello');
这不行:select.find('option')
.removeAttr('selected')
.eq(index).attr('selected', 'selected');
以下是目前的代码:
(function($){
$.fn.selectMenu = function() {
var select = this;
select.hide();
var title = select.attr('title');
var arrow = 'img/arrow.png';
var items = '';
select
.children('option')
.each(function(){
var item = $(this).text();
if ($(this).val() != '') {
$(this).attr('value', item);
}
items += '<li>' + item + '</li>'
});
var menuHtml =
'<ul class="selectMenu">' +
'<img src="' + arrow + '" alt=""/>' +
'<li>' + title + '</li>' +
'<ul>' + items + '</ul>' +
'</ul>';
select.after(menuHtml);
var menu = $(this).next('ul');
var list = menu.find('ul');
menu
.hover(function(){}, function(){
list.hide();
})
.children('li').hover(function(){
list.show();
});
menu.find('ul li').click(function(){
var index = $(this).index();
menu.children('li').text($(this).text());
select.find('option')
.removeAttr('selected')
.eq(index).attr('selected', 'selected');
list.hide();
});
};
})(jQuery);
.attr('selected', true)
吗? - NT3RP.attr('selected', true)
也不起作用。 - elclanrs