Jquery添加和删除输入

时间:2016-06-12 21:19:01

标签: jquery

熙!

我试图创建一个脚本,添加删除部分到字段集 https://jsfiddle.net/3kcoxsac/2/

现在添加部分工作正常,只有删除部分正在处理第一个div而不是新添加的

html:

<fieldset class="p-bottom-12 bg-white p-around-12 m-bottom-60 u-border-radius">
  <div id="js-artist" class="table u-border-box">
    <div class="js-artist u-flex-row p-top-12 u-border-top">
      <input class="m-left-24 small m-right-24 form-input w-100 cell-10 u-flex u-break" type="text" id="artiestNaam" placeholder="Artiest naam"><input class="form-input small m-right-24 w-100 cell-10 u-flex u-break form-error" type="url" id="artiestURL" placeholder="Artiestenpagina of website"><span class="js-removeArtist cell-w40 large cell-lineheigt u-pointer secondary_color-fixed"><i class="fa fa-trash-o" aria-hidden="true">R</i></span>
    </div>
  </div>
  <span id="js-addArtist">add</span>
</fieldset>

jquery:

 var artist = $('#js-artist'),
   i = 1;
 $('#js-addArtist').click(function() {
   $('<div class="js-artist u-flex-row p-top-12 u-border-top"><input class="m-left-24 small m-right-24 form-input w-100 cell-10 u-flex u-break" type="text" id="artiestNaam_' + i + '" placeholder="Artiest naam"><input class="form-input small m-right-24 w-100 cell-10 u-flex u-break" type="text" id="artiestURL_' + i + '" placeholder="Artiestenpagina of website"><span class="js-removeArtist cell-w40 large cell-lineheigt u-pointer secondary_color-fixed"><i class="fa fa-trash-o" aria-hidden="true">R</i></span></div>').appendTo(artist);
   i++;
 });
 $('.js-removeArtist').click(function() {
   alert();
   if (i > 1) {
     $(this).parents('.js-artist').remove();
     i--;
   }
 });

所以,如果你点击新添加的部分上的R,它不起作用,而我添加相同的html就是它的工作

1 个答案:

答案 0 :(得分:2)

问题在于,由于您要动态添加元素,因此必须将click事件绑定到文档,因为文档准备就绪时添加的元素不存在尝试:

 var artist = $('#js-artist'),
   i = 1;
 $('#js-addArtist').click(function() {
   $('<div class="js-artist u-flex-row p-top-12 u-border-top"><input class="m-left-24 small m-right-24 form-input w-100 cell-10 u-flex u-break" type="text" id="artiestNaam_' + i + '" placeholder="Artiest naam"><input class="form-input small m-right-24 w-100 cell-10 u-flex u-break" type="text" id="artiestURL_' + i + '" placeholder="Artiestenpagina of website"><span class="js-removeArtist cell-w40 large cell-lineheigt u-pointer secondary_color-fixed"><i class="fa fa-trash-o" aria-hidden="true">R</i></span></div>').appendTo(artist);
   i++;
 });
 $(document).on('click', '.js-removeArtist', function() {
   alert();
   if (i > 1) {
     $(this).parents('.js-artist').remove();
     i--;
   }
 });

这是更新的jsfiddle
https://jsfiddle.net/3kcoxsac/3/