jQuery jQuery中的逗号分隔列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5794707/
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
Comma separated list in jQuery
提问by Phillip Senn
I'm trying to create a comma separated list from what is checked on the form.
我正在尝试从表单上检查的内容中创建一个逗号分隔的列表。
var $StateIDs = $(':checked');
var StateIDs = '';
for (i=0, j = $StateIDs.length; i < j; i++) {
StateIDs += $StateIDs[i].val();
if (i == j) break;
StateIDs += ',';
}
There's probably a 1-liner that can do this, or a single function.
可能有一个 1-liner 可以做到这一点,或者一个单一的功能。
回答by John Strickler
map()is going to be your friend here.
map()将成为你的朋友。
var StateIDs = $(':checked').map(function() {
return this.value;
}).get().join(',');
StateIDs will be a comma-separated string.
StateID 将是一个逗号分隔的字符串。
Step-by-step - What is going on?
一步一步 - 发生了什么?
$(':checked')
// Returns jQuery array-like object of all checked inputs in the document
// Output: [DOMElement, DOMElement]
$(':checked').map(fn);
// Transforms each DOMElement based on the mapping function provided above
// Output: ["CA", "VA"] (still a jQuery array-like object)
$(':checked').map(fn).get();
// Retrieve the native Array object from within the jQuery object
// Output: ["CA", "VA"]
$(':checked').map(fn).get().join(',');
// .join() will concactenate each string in the array using ','
// Output: "CA,VA"
回答by Tim Joyce
var ids = '';
$(':checked').each(function(){
ids += $(this).val() + ',';
});
Writing blind, so I have not tested.
盲写,所以我没有测试。
回答by beardww
$.each([52, 97], function(index, value) {
alert(index + ': ' + value);
});
回答by Karelzarath
Check the second answer here. It gives you nicely simplified code for exactly what you're doing.