我正在制作一个选择菜单插件来替换丑陋的默认选择,并在不同的操作系统中保持一致.
这是演示(只有firefox和webkit)
http://spacirdesigns.com/selectMenu/
它已经工作了,但是我在选择“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);
解决方法
查看
this previous detailled answer on SO:
如果你真的想要使用selected属性来保持HTML输出,并且不仅让jQuery在select元素上保持正确的selectedindex属性,你可以使用原始的settAttr()函数进行破解:
select[0].options[select[0].selectedindex].setAttribute('selected','selected');
但是只要你继续使用jQuery方法进行val()或’:selected’,你就不应该遇到任何问题,只有当你解析HTML才能找到所选属性时才会遇到问题,这是你不应该做的事情,永远不会.