使用jQuery将选定属性添加到选择菜单中的选项

elc*_*nrs 8 jquery menu selected option

我正在制作一个选择菜单插件来替换丑陋的默认选择,并在不同的操作系统中保持一致.

这是演示(只有firefox和webkit)
http://spacirdesigns.com/selectMenu/

它已经可以工作了,但是我在向选项分配"selected"属性时遇到了问题.代码适用于任何其他属性,但我无法使用所选属性.

这有效:

select.find('option')
    .removeAttr('whatever')
    .eq(index).attr('whatever', 'hello');
Run Code Online (Sandbox Code Playgroud)

这不是:

select.find('option')
    .removeAttr('selected')
    .eq(index).attr('selected', 'selected');
Run Code Online (Sandbox Code Playgroud)

这是迄今为止的代码:

(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);
Run Code Online (Sandbox Code Playgroud)

sid*_*rcy 27

从jQuery 1.6开始"要检索和更改DOM属性,例如表单元素的选中,选中或禁用状态,请使用.prop()方法."

$("#someselect option[value=somevalue]").prop("selected", "selected")
Run Code Online (Sandbox Code Playgroud)

  • 这应该是最好的答案,比其他更老的答案要简单得多 (2认同)

reg*_*ero 5

在SO上查看先前的详细答案

如果您确实想保留具有selected属性的HTML输出,并且不仅让jQuery保留了select元素上正确的selectedIndex属性,还可以使用原始的settAttr()函数进行修改:

select[0].options[select[0].selectedIndex].setAttribute('selected','selected');
Run Code Online (Sandbox Code Playgroud)

但是,只要对val()或':selected'继续使用jQuery方法,就不会遇到任何问题,只有在解析HTML来查找所选属性时才可能出现问题,这是您不应该做的,永远不要。