Jquery .map().join(",")文本未加入逗号(,)

Gan*_*dav 4 jquery text dictionary join onchange

我正在使用label和隐藏输入checkbox.change复选框.我正在通过Jquery获取标签文本.map()并想要发.join(",")短信,.

文本即将到来,一切正常,但逗号(,)无论如何都不会出现.

我收到结果Checkbox 1Checkbox 2Checkbox 5我想要Checkbox 1,Checkbox 2,Checkbox 5

找小提琴演示

突出显示代码:

$(".combo").append( $(txt).map(function() {
    return $(this).text();
}).get().join( " ," ) );
Run Code Online (Sandbox Code Playgroud)

码:

var checked = [];
$('input[type="checkbox"]').change(function(e) {
    var num_checked = $('input[type="checkbox"]:checked').length;

    if (num_checked > 3) {
        checked[checked.length - 1].prop('checked', false);
        if(checked[checked.length - 1].prop('checked', false)){
            checked[checked.length - 1].parents('label').removeClass("active");
            var et = checked[checked.length - 1].parents('label').text();
            $('.combo').text(function () {
                return $(this).text().replace(et, '');  
            });

        }
        checked.pop();
    }
    if($.inArray($(this), checked) < 0){
        checked.push($(this));
        if($(this).is(':checked')){
            $(this).parents('label').addClass("active");
            var txt = $(this).parents('label');
            $(".combo").append( $(txt).map(function() {
                return $(this).text();
            }).get().join( " ," ) );

        } else{
            $(this).parents('label').removeClass("active-cb");
            //$('.selectedSwitch').text('');
            var qr = $(this).parents('label').text();
            $('.combo').text(function () {
                return $(this).text().replace(qr, '');  
            });
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

jma*_*777 8

我担心你可能在这里过度设计了你的解决方案.请看这个简化版本:

$('input[type="checkbox"]').change(function(e) {
    // just grab the labels for all checked inboxes...
    var txt = $('input:checked').closest('label')
        // then map that collection to their text values
        .map(function() { return $(this).text(); })
        // and format into your comma-delineated list
        .get().join(', ');

    $('.combo').text(txt);
});
Run Code Online (Sandbox Code Playgroud)

你可以在这里看到它:https://jsfiddle.net/usx8Lkc5/11/