首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Jquery添加和删除输入

Jquery添加和删除输入
EN

Stack Overflow用户
提问于 2016-06-12 21:19:00
回答 1查看 39关注 0票数 0

嘿嘿!

我正在尝试创建一个脚本,在字段集https://jsfiddle.net/3kcoxsac/2/中添加en移除部件

现在添加部分工作得很好,只有删除部分才能在第一个div上工作,而不是在新添加的

html:

代码语言:javascript
复制
<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:

代码语言:javascript
复制
 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与其工作的html相同。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-06-12 21:23:52

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

代码语言:javascript
复制
 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--;
   }
 });

这是最新的快捷键

https://jsfiddle.net/3kcoxsac/3/

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37779181

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档