如何在javascript中添加克隆计数器ID

时间:2017-07-17 10:22:29

标签: javascript jquery

我不知道把柜台放在哪里;     下一个克隆的ID必须是gender_1

示例:

<select id="gender">

Next is:
`<select id="gender_1">`

then:
`<select id="gender_2">`

https://jsfiddle.net/f7hjh1gf/6/

2 个答案:

答案 0 :(得分:2)

尝试这一点,在附加到元素之前,您需要使用id函数替换克隆的选定元素find()并使用id更新c++

Updated jsfiddle

$(document).ready(function(){
var c=1;
    $(document).on('click', '#mode', function(){
        $("#notok").clone(true).find('select').attr('id','gender_'+(c++) ).closest('.ok').appendTo("#clones");
    });
});

答案 1 :(得分:1)

每次添加克隆时,都会获取已存在的克隆数,并在将其添加到&#34; gender _&#34;之前将其递增1,您可以使用$("#clones div").length来获取当前存在的克隆数。 / p>

&#13;
&#13;
$(document).ready(function(){
    $(document).on('click', '#mode', function(){
        $("#notok").clone(true).attr('id', "gender_"+($("#clones div").length + 1)).appendTo("#clones");
    });
});
&#13;
<div class="container">

<div class="ok" id="notok">
	<select id="gender">
    	<option value="Male">Male</option>
        <option value="Female">Female</option>
    </select>

    
</div>

<div id=clones></div>

<button id="mode">Clone</button>


  

  <!-- Modal -->
  <div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">

  <!-- Modal content-->
  <div class="modal-content">
    <div class="modal-header">
      <button type="button" class="close" data-dismiss="modal">&times;</button>
      <h4 class="modal-title">Modal Header</h4>
    </div>
    <div class="modal-body">
      <p>Some text in the modal.</p>
    </div>
    <div class="modal-footer">
      <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
    </div>
  </div>
  
</div>
  </div>
  
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;