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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5790668/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 19:49:22  来源:igfitidea点击:

Add selected attribute to option in select menu with jQuery

jquerymenuoptionselected

提问by elclanrs

I'm making a select menu plugin to replace the ugly default selects and be consistent across different OS.

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

Here's the demo (only firefox and webkit)
http://spacirdesigns.com/selectMenu/

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

It's already working, but I'm having problems assigning the "selected" attribute to the option. The code works with any other attribute but I can't get it to work with the selected attribute.

它已经可以工作了,但是我在将“selected”属性分配给选项时遇到了问题。该代码适用于任何其他属性,但我无法使其与所选属性一起使用。

This works:

这有效:

select.find('option')
    .removeAttr('whatever')
    .eq(index).attr('whatever', 'hello');

This doesn't:

这不会:

select.find('option')
    .removeAttr('selected')
    .eq(index).attr('selected', 'selected');

And here's the code so far:

这是到目前为止的代码:

(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);

采纳答案by regilero

Check out this previous detailled answer on SO:

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

If you really want to maitain HTML output with selected attribute, and not only have jQuery maitaining the right selectedIndexattribute on the select element, you can hack with original settAttr() function:

如果您真的想使用 selected 属性维护 HTML 输出,并且不仅让 jQuery 维护select 元素上的正确selectedIndex属性,您还可以使用原始 settAttr() 函数进行破解:

select[0].options[select[0].selectedIndex].setAttribute('selected','selected');

But as soon as you keep using jQuery methods for val() or ':selected', you should'nt get any problem, you could have problem only if you were parsing HTML to find selected attribute, something you should'nt do, never.

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

回答by sidarcy

As of jQuery 1.6 "To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method."

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

$("#someselect option[value=somevalue]").prop("selected", "selected")

回答by Kristoffer Lundberg

Considering your latest comment I assume your problem is firebug, not your code. Why this works with other attributes except "selected", is that selecting an option from the dropdown doesn't modify the selected attribute in the DOM. I assure you, there's nothing wrong with your code.

考虑到您的最新评论,我认为您的问题是萤火虫,而不是您的代码。为什么这适用于除“selected”之外的其他属性,是从下拉列表中选择一个选项不会修改 DOM 中的 selected 属性。我向你保证,你的代码没有任何问题。