简体   繁体   English

jQuery删除父字段集

[英]jQuery Remove Parent Fieldset

I have a form that has multiple instances of the same field set. 我有一个具有相同字段集的多个实例的表单。 You can add more field sets by clicking "Add a Field." 您可以通过单击“添加字段”来添加更多字段集。

The page starts with 5 field sets. 该页面以5个字段集开头。 If you click "Remove," the background color will change to red (so that you can tell which field set would be removed). 如果单击“删除”,则背景色将变为红色(这样您就可以知道将删除哪个字段集)。

If you add more fields, those field sets will not respond to the "Remove" button even though they have the exact same code as the ones that the page starts out with, and they are added to the same form. 如果添加更多字段,则即使这些字段集具有与页面开始时使用的代码完全相同的代码,并且将它们添加到相同的表单中,这些字段集也不会响应“删除”按钮。

Can you please take a look at my code and let me know why the added fields will not remove whereas the ones that start out on the page remove? 您能否看一下我的代码,让我知道为什么添加的字段不会被删除,而页面上开始的字段却被删除了?

https://jsfiddle.net/Lc510xmn/1/ https://jsfiddle.net/Lc510xmn/1/

// Adds a new field set to the form

$('[data-action="addField"]').click(function(){
        var fieldSet = '<fieldset><input type="text" name="field"><button type="button" data-action="removeField">Remove</button></fieldset>';
        $('form').append(fieldSet);
  return false;
});

// Changes the background to red instead of removing

$('[data-action="removeField"]').click(function(){
    $(this).parents('fieldset').css('background-color','red');
return false;
});

The bound events doesn't work for dynamically added/created elements, so you need to delegate the event to very first parent that will not be manipulate dynamically (using jQuery or JavaScript ). 绑定事件不适用于动态添加/创建的元素,因此您需要将事件委托给不会动态处理(使用jQueryJavaScript )的第一个父对象。

From jQuery documentation : jQuery文档中

// jQuery 1.4.3+
$( elements ).delegate( selector, events, data, handler );
// jQuery 1.7+
$( elements ).on( events, selector, data, handler );

Also you can read Event binding on dynamically created elements . 您还可以阅读动态创建的元素上的事件绑定


So you should change your code like this: 因此,您应该像这样更改代码:

// jQuery 1.7+
$('form').on('click', '[data-action="removeField"]', function() {
    $(this).parents('fieldset').css('background-color', 'red');
    return false;
});

Updated js fiddle is here https://jsfiddle.net/Lc510xmn/2/ 更新的js小提琴在这里https://jsfiddle.net/Lc510xmn/2/

$(function(){

    $('[data-action="addField"]').click(function(){
            var fieldSet = '<fieldset><input type="text" name="field"><button type="button" data-action="removeField">Remove</button></fieldset>';
            $('form').append(fieldSet);
      return false;
    });

    $("#fields").on("click", '[data-action="removeField"]', function(event){
        $(this).parents('fieldset').css('background-color','red');
    return false;
    });

});

试试这个$(this).parents('fieldset').remove()

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

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