使用jQuery查找多个选择框的标签

时间:2011-11-28 13:03:29

标签: jquery

我有this script

我想要达到这个HTML:

City
 Paris
 Bern
Sex
 Male
 Female

但是使用我的脚本,标签会在更改时互相替换。我怎样才能获得上面的HTML? 提前致谢

脚本:

$("select").change(function () {
  var str = "";
  var id = $(this).attr('id');
  var label = '<li><b>'+$("label[for='" + id + "']").text()+'</b> </li>';
  $("select option:selected").each(function () {
        str += '<li>'+$(this).text()+'</li>';
      });
  $("ul").html(label + str);
})
.trigger('change');

HTML:

<label for="sex">sex</label>
<select id="sex" multiple="multiple">
    <option>Male</option>
    <option>Female</option>
</select>
<label for="city">City</label>
<select id="city" multiple="multiple">
    <option>Paris</option>
    <option>Bern</option>
</select>
<ul></ul>

1 个答案:

答案 0 :(得分:2)

试试这个小提琴:http://jsfiddle.net/XWr4W/2/

$("select").change(function() {
    var str = "";

    // Only loop through selects which have selected elements
    $("select:has(:selected)").each(function() {

        var id = $(this).attr('id');
        str += '<li><b>' + $("label[for='" + id + "']").text() + '</b> </li>';

        // Loop through the selected elements of this SELECT
        $(this).find("option:selected").each(function() {
            str += '<li>' + $(this).text() + '</li>';
        });
    });
    $("ul").html(str);
}).trigger('change');