简体   繁体   English

使用jQuery删除单击时的父元素

[英]Removing a parent element on click using jQuery

I am having trouble creating a dynamic form where a user can add and remove a text field. 我在创建动态表单时遇到麻烦,用户可以在其中添加和删除文本字段。 The functionality to add an extra field works fine, but removing the field just cannot seem to work. 添加额外字段的功能可以正常工作,但是删除该字段似乎无法正常工作。

My html is: 我的html是:

<div class="formItem" id="members">
  <label for="workgroup">Add Members:</label>
  <br />
  <a href="#" id="addMember">Add another member</a>
  <p>
    <input type="text" name="members[]" placeholder="Enter email" autocomplete="off" />
  </p>
</div>

My JS: 我的JS:

$('#addMember').on('click', function() {
  $('<p><input type="text" name="members[]" placeholder="Enter email" autocomplete="off" /><a href="#" id="removeMember">Remove</a></p>').appendTo('#members');
  return false;
});

$('#removeMember').on('click', function() {
  $(this).parent().remove();
});

You are adding the click listener before actually creating the element, use: 您要在实际创建元素之前添加点击侦听器,请使用:

$('#members').on('click', '#removeMember', function() {
  $(this).parent().remove();
});

see these examples http://api.jquery.com/on/#entry-examples 请参阅以下示例http://api.jquery.com/on/#entry-examples

try using this 尝试使用这个

$(document).on('click','#removeMember', function() {
    $(this).parent().remove();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM