如何用字符分隔返回的结果?

时间:2013-11-26 15:36:16

标签: javascript jquery

我有一个复选框列表,我收到每个复选框的标签字符串,每个复选框用逗号分隔。 标签是输入框的兄弟。我可以获取文本,但如何添加逗号?

以下是我的HTML的信息:

...
...
<div class="ui-checkbox">
    <input id="abc" value="1" type="checkbox">
    <label for="abc">
        <span>
            <span class="ui-btn-text">Two Words</span>
        </span>
    </label>
</div>
<div class="ui-checkbox">
    <input id="abc" value="1" type="checkbox">
    <label for="abc">
        <span>
            <span class="ui-btn-text">Joe</span>
        </span>
    </label>
</div>
...
...

我的jQuery内容:

string = $('input:checked').siblings($("ui-btn-text")).text();

这给出了以下结果: “Foo Bar Meth Two Words Joe”

但我想要: “Foo,Bar,Meth,Two Words,Joe”

我可以在这里添加什么来获取逗号?

2 个答案:

答案 0 :(得分:2)

尝试:

$('input:checked').next().find(".ui-btn-text").map(function(){
      return $.trim(this.innerHTML);
}).get().join(', '); //If you do not want a space after comma then just .join()

<强> Demo

答案 1 :(得分:1)

string = $('input:checked').next().map(function () {
    return $.trim($(this).text())
}).get().join();

演示:Fiddle

相关问题