javascript 从 jQuery 中的选择元素生成逗号分隔的字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21819475/
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
Generating a comma delimited string, from select element in jQuery
提问by wribit
Here's what's going on. I have a select element, for which I need to get a comma delimited string of all its options, regardless of whether or not it's selected.
这是怎么回事。我有一个 select 元素,我需要获取所有选项的逗号分隔字符串,无论它是否被选中。
How can I, in jQuery/javascript take this:
我怎样才能在 jQuery/javascript 中使用这个:
<select id="currentTags" multiple>
<option>Nature</option>
<option>Cats</option>
<option>Space</option>
</select>
and turn it into this:
并将其变成这样:
"Nature, Cats, Space"
I tried to find ways of doing this and couldn't... I'm still learning javascript, and my limited knowledge is stopping me in my tracks.
我试图找到这样做的方法,但不能......我仍在学习 javascript,我有限的知识阻止了我的学习。
Any help would be appreciated, even if it's just to guide me in the right direction. Thank you for your time.
任何帮助将不胜感激,即使只是为了指导我朝着正确的方向发展。感谢您的时间。
回答by elclanrs
With jQuery:
使用 jQuery:
var result = $('#currentTags option').map(function(i, opt) {
return $(opt).text();
}).toArray().join(', ');
In plain JavaScript you can do something similar like this:
在普通的 JavaScript 中,你可以做类似这样的事情:
// Convert pseudo-arrays to real arrays
var __slice = Array.prototype.slice;
// Get select options as real array
var opts = __slice.call(document.querySelectorAll('#currentTags option'));
// Map the text of each option
var result = opts.map(function(x) {
return x.textContent;
}).join(', ');
console.log(result); //=> "Nature, Cats, Space"
The advantage of abstracting elements into collections instead of looping is that you maintain a consistent API (like jQuery), and you don't need to create extra variables to loop pseudo-arrays, as real arrays can use all array methods.
将元素抽象成集合而不是循环的好处是你维护了一致的 API(如 jQuery),并且你不需要创建额外的变量来循环伪数组,因为真正的数组可以使用所有数组方法。
See the MDNto learn more about the DOM and the methods and properties you can use, like querySelectorAll
, children
, textContent
and more.
见MDN以了解更多有关DOM和可以使用的方法和属性,如querySelectorAll
,children
,textContent
等等。
Edit:This should work in IE9+ and all modern browsers.
编辑:这应该适用于 IE9+ 和所有现代浏览器。
回答by Littm
A simple solution would be:
一个简单的解决方案是:
// Initialize your string
var output_string = "";
// For each 'option' tag, append its value to the string with the comma
$('#currentTags option').each(function() {
output_string = output_string+this.text;
});
// Removing the last ', ' which were added during the loop
output_string = output_string.substr(0, output_string.length-2);
回答by RobG
The plain old javascript (POJS) way is to get the select's options collection, then loop over it to get the values and generate a string with the required format, e.g.
普通的旧 javascript (POJS) 方法是获取选择的选项集合,然后循环遍历它以获取值并生成具有所需格式的字符串,例如
var options = document.getElementById('currentTags').options;
var values = [];
for (var i=0, iLen=options.length; i<iLen; i++) {
values.push(options[i].text);
}
alert(values.join(','));
You can write that in much more concise form but performance may suffer and depending on features used, may fail in some browsers. The above puts a premium on clarity and maintainability of code, performance will be at least as fast as any alternative.
您可以以更简洁的形式编写它,但性能可能会受到影响,并且根据所使用的功能,在某些浏览器中可能会失败。上面强调代码的清晰度和可维护性,性能将至少与任何替代方案一样快。
回答by Julien Iafrancesco
How about just:
怎么样:
var tags = [];
$('#currentTags option').each(function() {
tags.push($(this).val());
});
console.log(tags.join(', ')); // 'Nature, Cats, Space'
回答by Tomanow
Here is a simple jQuery example:
这是一个简单的 jQuery 示例:
var arr = []; // create array
$('#currentTags').children().each(function() {
arr.push($(this).text()); // add option text to array
});
alert(arr.join(', ')); // Nature, Cats, Space
If you want the option value
, switch text()
to val()
;)
如果你想要这个选项value
,切换text()
到val()
;)