jQuery中用逗号分隔的多个列表项

时间:2018-09-17 16:29:30

标签: jquery

我有以下代码。

<div class="form-multiassign-add  binded" id="property_groupids">
        <div class="form-multiselectbox wide4 assigned">
            <div class="title"><div class="pad5-left pad5-top left font13">Selected Properties</div>
            <div class="button action right addbutton binded" id="addbutton"><i class="add"></i> Add</div>
        </div>
        <ul class="ui-sortable">
            <li id="selected-property_groupids-484645" data-listid="484645" data-all-properties="admin" style="background:#E5E5E5;">
            <label><i class="delete" title="Remove"></i>00New</label><input type="hidden" name="property_group[][ids]" value="484645"></li>
            <li id="selected-property_groupids-21458" data-listid="21458" data-all-properties="admin" style="background:#E5E5E5;">
            <label><i class="delete" title="Remove"></i>13th North Avenue</label><input type="hidden" name="property_group[][ids]" value="21458"></li>
        </ul>
    </div>

我只想要李的身份证。单击addbutton链接后,将添加新的li。 必需的结果-

<input type="hidden" id="selected_li_ids" value="484645,21458" />

我这样尝试-

$('#property_groupids .ui-sortable li').each(function(){
    ids[] = $(this).data('listid');
 });
$('#selected_li_ids').val(ids);

但是它不起作用。任何帮助。

2 个答案:

答案 0 :(得分:0)

使用此代码:

var ids = [];
$('#property_groupids .ui-sortable li').each(function(i,e){
    ids.push($(e).data('listid'));
});
$('#selected_li_ids').val(ids.join(","));

考虑@freedomn -m建议:

ids = $.map($('#property_groupids .ui-sortable li'),function(n, i){
    return $(n).data('listid');
});
idsString = Object.values(ids).join(",");
$('#selected_li_ids').val(idsString);

答案 1 :(得分:0)

据我了解,您需要属性data-listid

var ids = [];
$("li").each(function(){
ids.push($(this).attr("data-listid"));
});

//put hidden instead of text
$("#property_groupids").append('<input type="text" id="selected_li_ids" value="'+ids.join(",")+'" />');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-multiassign-add  binded" id="property_groupids">
        <div class="form-multiselectbox wide4 assigned">
            <div class="title"><div class="pad5-left pad5-top left font13">Selected Properties</div>
            <div class="button action right addbutton binded" id="addbutton"><i class="add"></i> Add</div>
        </div>
        <ul class="ui-sortable">
            <li id="selected-property_groupids-484645" data-listid="484645" data-all-properties="admin" style="background:#E5E5E5;">
            <label><i class="delete" title="Remove"></i>00New</label><input type="hidden" name="property_group[][ids]" value="484645"></li>
            <li id="selected-property_groupids-21458" data-listid="21458" data-all-properties="admin" style="background:#E5E5E5;">
            <label><i class="delete" title="Remove"></i>13th North Avenue</label><input type="hidden" name="property_group[][ids]" value="21458"></li>
        </ul>
    </div>