我正在使用一个选择框来克隆一个 div(基于数字选择)并增加新 div 的 ID 和标签。我有这个工作,但我的问题是,如果你选择一个大于 2 的数字,div 不会按顺序递增。如果您选择 2 然后 3 然后 4 等等,他们会这样做。
基本上,如果您在选择框中选择 3,我希望结果为:
成人会员计划 #1
成人会员计划 #2 成人
会员计划 #3
而不是:
成人会员计划 #1
成人会员计划 #3 成人
会员计划 #2
这是我的JS:
$(document).ready(function () {
//onchange of rooms-count
$('#num-adults').change(function() {
var roomsSelected = $('#num-adults option:selected').val();
var roomsDisplayed = $('[id^="program-"]:visible').length;
var roomsRendered = $('[id^="program-"]').length;
if (roomsSelected > 0) {
$('.membership-programs.adult label').show();
}
else {
$('.membership-programs.adult label').hide();
}
//if room count is greater than number displayed - add or show accordingly
if (roomsSelected > roomsDisplayed) {
for (var i=1;i<=roomsSelected;i++){
var r = $('#program-' + i);
if (r.length == 0) {
var clone = $('#program-1').clone(); //clone
clone.children(':first').text("Membership Program for Adult #"+i);
//change ids appropriately
setNewID(clone, i);
clone.children('div').children('select').each(function() {
setNewID($(this),i);
});
$(clone).insertAfter($('#program-'+roomsRendered));
}
else {
//if the room exists and is hidden
$(r).show();
}
}
}
else {
//else if less than room count selected - hide
for (var i=++roomsSelected;i<=roomsRendered;i++){
$('#program-'+i).hide();
}
}
});
function setNewID(elem, i) {
oldID = elem.attr('id');
newId = oldID.substring(0, oldID.indexOf('-')) + "-" + i;
elem.attr('id',newId);
}
});
这是我的 HTML:
<div id="hotel-guests">
<span class="wrapper">
<label for="num-adults"># of Adults:</label>
<select tabindex="4" name="amtrakadults" id="num-adults" class="traveler-dropdown">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
</select>
</span>
</div>
<div class="membership-programs adult">
<div id="program-1" class="program">
<span>Membership Program for Adult #1:</span>
<span class="wrapper">
<select tabindex="4" name="program" class="membership-program">
<option value="None">None</option>
<option value="AAA">AAA</option>
<option value="Student Advantage">Student Advantage</option>
<option value="Veterans Advantage">Veterans Advantage</option>
<option value="NARP">NARP</option>
<option value="ISIC">ISIC</option>
</select>
</span>
</div>
</div>
这是一个显示问题的小提琴。