繁体   English   中英

jQuery删除父字段集

[英]jQuery Remove Parent Fieldset

我有一个具有相同字段集的多个实例的表单。 您可以通过单击“添加字段”来添加更多字段集。

该页面以5个字段集开头。 如果单击“删除”,则背景色将变为红色(这样您就可以知道将删除哪个字段集)。

如果添加更多字段,则即使这些字段集具有与页面开始时使用的代码完全相同的代码,并且将它们添加到相同的表单中,这些字段集也不会响应“删除”按钮。

您能否看一下我的代码,让我知道为什么添加的字段不会被删除,而页面上开始的字段却被删除了?

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;
});

绑定事件不适用于动态添加/创建的元素,因此您需要将事件委托给不会动态处理(使用jQueryJavaScript )的第一个父对象。

jQuery文档中

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

您还可以阅读动态创建的元素上的事件绑定


因此,您应该像这样更改代码:

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

更新的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