无法从动态列表

时间:2017-01-20 09:38:41

标签: jquery

当我点击任何select元素时,它返回select id而不是父id。我做错了什么?我需要父ID来操作选择元素

var index = $("#olcityList li").length;
var $li = $('li.list');

$('#plus').click(function() {
  index = index + 1;

  $('li.list').last().after($li.clone());

  $(this).attr('id', 'listId_' + (index)).attr('class', ' ');
  $('li.list div.city select').last().attr('id', 'cityList_' + (index));
  $('li.list div.esta select').last().attr('id', 'estaList_' + (index));

  // Get the select id and its parent id 
  $('body').on('click', 'select', function() {
    $('#olcityList li:last').attr('id', 'listId_' + (index));

    var appendedlistId = $('li.list').last().attr('id');
    

    console.log("Parent id:" + $('select').closest('li').attr('id'));
    
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <input id="plus" type="button">
  <input id="minus" type="button">
  <input id="getEachId" type="button">
</div>
<ol id="olcityList">
  <li class="list" id="listId_1">
    <div class="city">
      <select id="cityList_1"></select>
    </div>
    <div class="esta">
      <select id="estaList_2"></select>
    </div>
  </li>
</ol>

截至目前,它返回与select id相同的父ID 和li的父ID:第一个元素始终是附加的li:元素

1 个答案:

答案 0 :(得分:0)

您没有正确创建元素,也没有将事件处理程序移到#plus按钮单击事件处理程序之外。

当您想要clone() DOM片段时,获取对clone元素的引用,然后对其执行所有操作。例如,下面的语句实际上将操纵DOM而不是克隆对象。

$('li.list div.city select').last().attr('id', 'cityList_' + (index));

除此之外,您始终使用ID

设置.attr('id', 'listId_' + (index));

以下是代码

&#13;
&#13;
var list = $("#olcityList");

//Create clone for initial element
var $li = $('li.list').clone();

$('#plus').click(function() {
  var index = list.find("li").length + 1;
  
  //Create clone to manipulate its elements
  var li = $li.clone();
  li.attr('id', 'listId' + index);
  li.find('.city select').attr('id', 'cityList_' + index);
  li.find('.esta select').attr('id', 'estaList_' + index);
  
  //Append
  list.append(li);
});

// Get the select id and its parent id 
list.on('click', 'select', function() {
  console.log("parent id: " + $(this).closest('li').attr('id'));
  console.log("Current id: " + $(this).attr('id'));
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <button id="plus" type="button"> +</button>
</div>
<ol id="olcityList">
  <li class="list" id="listId_1">
    <div class="city">
      <select id="cityList_1"></select>
    </div>
    <div class="esta">
      <select id="estaList_1"></select>
    </div>
  </li>
</ol>
&#13;
&#13;
&#13;