javascript 将列表框中的所有选项转换为逗号分隔的字符串的惯用 jQuery?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4199826/
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-10-25 10:40:25  来源:igfitidea点击:

Idiomatic jQuery to get all options in a listbox into comma-separated string?

javascriptjquerydom

提问by Cade Roux

Where lb is a listbox, txtfield is a textbox, this code takes all the values of the options, puts them in an array and makes it into a comma-separated list:

其中 lb 是一个列表框,txtfield 是一个文本框,此代码获取选项的所有值,将它们放入一个数组中并使其成为一个逗号分隔的列表:

var arr = [];
for (var i = 0; i < lb.length; i++) {
    arr[i] = lb.options[i].value;
}
txtfield.value = arr.join(',');

lb.options.toString() obviously doesn't work because it's an array of options (value and text). I haven't found anything more succint than this.

lb.options.toString() 显然不起作用,因为它是一组选项(值和文本)。我还没有找到比这更简洁的东西。

What's the jQuery way to do this? I tried messing around with $(lb).each(), but can't seem to get it to work in the same way.

什么是 jQuery 方法来做到这一点?我尝试使用$(lb).each(),但似乎无法以相同的方式工作。

回答by user113716

txtfield.value = $(lb.options).map(function() { 
                                       return this.value; 
                                   }).get().join(',');

This uses .map()to create a jQuery object by returning the valueof each option, then uses .get()to extract the Array from the object.

用于.map()通过返回valueeach 的来创建一个 jQuery 对象option,然后用于.get()从对象中提取 Array。



EDIT:As @Nick Cravernoted in the comment below, if you need to get optimal performance (with jQuery), it makes more sense to use the $.map()variationsince you already have a collection. See his answerfor details.

编辑:作为@Nick Craver在下面的评论指出,如果需要获得最佳性能(使用jQuery),它使得使用更有意义$.map()变化,因为你已经有一个集合。详情见他的回答



EDIT:To get better performance, do your forloop, but cache the references to the properties. It makes a difference.

编辑:为了获得更好的性能,请执行for循环,但缓存对属性的引用。它有所作为

var arr = [], opts = lb.options, len = opts.length;
for (var i = 0; i < len; i++) {
    arr[i] = opts[i].value;
}
txtfield.value = arr.join(',');

回答by Nick Craver

The jQuery version is .map()like this:

jQuery 版本是.map()这样的:

var arr = $(lb).find("option").map(function() { return this.value; }).get();
txtfield.value = arr.join(',');

Or a bit faster with $.map()like this:

或者$.map()像这样更快一点:

var arr = $.map(lb.options, function(o) { return o.value; });
txtfield.value = arr.join(',');

However, both are significantly less efficientthan a forloop, go with the plain JavaScript version you already have.

然而,无论是显著低效率for循环,你已经拥有了普通的JavaScript版本去。

回答by Quintin Robinson

Look at map()..

map()..

$('#lbID option').map(function() {
  return $(this).val();
}).get().join(',');

回答by jwueller

This is the jQuery equivalent to your code. There are more elegant solutions, though.

这是与您的代码等效的 jQuery。不过,还有更优雅的解决方案。

var values = [];

$(lb).children('option').each(function () {
   values.push($(this).text());
});

$(txtfield).val(values.join(','));

回答by El Ronnoco

Could do it like this but I'm not sure what you're trying to achieve?

可以这样做,但我不确定你想要达到什么目标?

$('option', $(lb)).each(function() { arr.push($(this).text()) });

回答by Jaydeep Shil

See demo here: Fiddler Demo

在此处查看演示:Fiddler 演示

you can get the multiple selected option Text values with separator.

您可以使用分隔符获取多个选定选项文本值。

 $('#testID').change(function () {
        var test=$(this).find("option:selected").map(function () {
        return $(this).text();
    }).get().join('//');
     alert(test);
            });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="testID" multiple="multiple">
    <option value="1">test Value1</option>
    <option value="2">test Value2</option>
    <option value="3">test Value3</option>
    <option value="4">test Value4</option>
    <option value="5">test Value5</option>
    <option value="6">test Value6</option>
</select>
<input type="button" value="Get dropdown selected Value" id="select-values">
    <div id="result"></div>