Html,使用增量 ID 克隆 select 选项在第一次克隆时不起作用

Html, cloning select option with increment id doesn't work on first clone

我有 html 和 jquery 依赖 select 选项国家和城市的代码示例,带有用于复制更多 select 选项的按钮,如下所示:

var $duplicate = $('.record').first().clone(true);
var $form = $('.form');
var count = 1;

$('#add_record').click(function() {
  count += 1;
  $form.append($duplicate.clone());
  $($duplicate).find("*[id]").each(function() {
    $(this).val('');
    var tID = $(this).attr("id");
    var idArray = tID.split("_");
    var idArrayLength = idArray.length;
    var newId = tID.replace(idArray[idArrayLength - 1], count);
    $(this).attr('id', newId);
  });
})

$('.form').on('change', '.country', function() {
  var val = $(this).val();
  var $city = $(this).closest('.record').find('.city');
  if (val == "germany") {
    $city.html("<option>Berlin</option> <option>Munich</option>");
  } else if (val == "england") {
    $city.html("<option>London</option> <option>Manchester</option>");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form">
  <div class="record">
    <label>Country</label>
    <select class="country" id="country_1">
      <option disabled selected></option>
      <option value="germany">Germany</option>
      <option value="england">England</option>
    </select>
    <label>City</label>
    <select class="city" id="city_1">
      <option disabled selected></option>
    </select>
  </div>
</form>
<button type="button" id="add_record">add</button>

在 jquery 克隆的 select 选项中,不同的 id 递增 1,但只有第一个克隆的元素递增 id 不起作用,其余的都很好。你能帮我想念什么吗?谢谢。

您应该在 $(duplicate) 中增加 ID,然后再 克隆它。否则,第一个副本与您从中克隆它的原始记录具有相同的 ID。

var $duplicate = $('.record').first().clone(true);
var $form = $('.form');
var count = 1;

$('#add_record').click(function() {
  count += 1;
  $($duplicate).find("*[id]").each(function() {
    $(this).val('');
    var tID = $(this).attr("id");
    var idArray = tID.split("_");
    var idArrayLength = idArray.length;
    var newId = tID.replace(idArray[idArrayLength - 1], count);
    $(this).attr('id', newId);
  });
  $form.append($duplicate.clone());
})

$('.form').on('change', '.country', function() {
  var val = $(this).val();
  var $city = $(this).closest('.record').find('.city');
  if (val == "germany") {
    $city.html("<option>Berlin</option> <option>Munich</option>");
  } else if (val == "england") {
    $city.html("<option>London</option> <option>Manchester</option>");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form">
  <div class="record">
    <label>Country</label>
    <select class="country" id="country_1">
      <option disabled selected></option>
      <option value="germany">Germany</option>
      <option value="england">England</option>
    </select>
    <label>City</label>
    <select class="city" id="city_1">
      <option disabled selected></option>
    </select>
  </div>
</form>
<button type="button" id="add_record">add</button>