我有一个多元素和依赖div,它要求用户首先选择一个状态。一旦选择了该州,它将为用户提供该州合适的城市。
<form method="post">
<div class="summary">
<div class="trip">
<select name="State" class="state">
<option selected disabled>Choose a State</option>
<option>California</option>
<option>New York</option>
</select>
<select name="City" class="city" disabled="true">
<option value="Z">Select a city</option>
</select>
<br><br>
</div>
</div>
jQuery:
$(document).ready(function() {
$("#result").hide();
$("form").on("change", "select", function(){
var current = $(this).index();
if($(this).eq(current).val() == 'Z') {
$(".city").eq(current).html("<option>Select a city</option>");
$(".city").eq(current).attr('disabled', true);
}
else {
if($(this).eq(current).val() == 'California') {
$(".city").eq(current).html("<option>San Francisco</option><option>Los Angeles</option>");
$(".city option:first").eq(current).attr('selected', 'selected');
$(".city").eq(current).attr('disabled', false);
}
if($(this).eq(current).val() == 'New York') {
$(".city").eq(current).html("<option>New York City</option><option>Albany</option>");
$(".city option:first").eq(current).attr('selected', 'selected');
$(".city").eq(current).attr('disabled', false);
}
}
});
var maxAppend = 0;
$("#add").click(function() {
if (maxAppend >= 4) return;
var additional = $(".trip").html();
$(".trip").after(additional);
maxAppend++;
});
});
我想允许用户最多添加四次类“trip”。当我使用append()或after()时,如上所示。新添加项的索引为1,这会导致在第一次行程中选择的重置,因为它具有相同的索引。实现这一点的正确和优雅的方式是什么?
以下是JSFIDLE的链接:
https://jsfiddle.net/L2bfmo69/