我想要达到这个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>
答案 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');