在jQuery中的逗号分隔列表 [英] Comma separated list in jQuery

查看:203
本文介绍了在jQuery中的逗号分隔列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试从表单上检查的列表中创建逗号分隔列表。

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.

推荐答案

map()

var StateIDs = $(':checked').map(function() { 
    return this.value; 
}).get().join(',');

StateID将是以逗号分隔的字符串。

StateIDs will be a comma-separated string.

分步骤 - 发生了什么?

$(':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"

这篇关于在jQuery中的逗号分隔列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆