我无法绑定事件来删除jQuery中的字段

时间:2017-12-13 19:46:17

标签: javascript jquery object-literal

我在jQuery中创建这个脚本来添加和删除字段,首先我以对象文字方式分隔函数,然后我可以通过克隆div来添加字段。但我无法将删除按钮绑定到克隆元素。

 <!--html with text field -->   
 <div class="row" id="descripcion_pregrado">
     <div class="col-xs-8 col-sm-8 col-lg-8">
         <div class="form-group">
            {{ Form::label('descripción', 'Descripción: *')}}
            {!! Form::text('descripcion_pregrado[]',null,
                            array(
                            'class'=>'form-control'
                             )) !!}
        </div>  
    </div>
    <div class="col-xs-3 col-sm-3 col-lg-3">
        <div class="form-group">
            {{ Form::label('dedicacion', 'Dedicación Horas Semanales: *') }}
            {!! Form::number('dedicacion_pregrado[]',0,
                            array(
                            'class'=>'form-control',
                            'min'=>0,
                            'step'=>'.01'
                             )) !!}
        </div>  
    </div>
    <div class="col-xs-1 col-sm-1 col-lg-1" style="padding-top:0px">    
        <div class="form-group">
            <a href="javascript:void(0);" class="add_button plus-minus" title="Add field"> <span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span></a>
        </div>
    </div>
</div>

以下是与add字段一起使用的jQuery,但它不包含remove field

(function () {

    var campos = {
        config: {
            start: 0,
            max: 9,
        },
        init: function (config) {
            $.extend(campos.config.config);
            this.cacheDom();
            this.bind();
        },
        cacheDom: function () {
            this.$el = $("#descripcion_pregrado");
            this.$button = this.$el.find("a");
            this.$remove = this.$el.find(".remove_button");

        },
        bind: function () {
            this.$button.on('click', this.addField.bind(this));
            this.$remove.on('click', this.removeField.bind(this));
        },
        addField: function () {
            if (campos.config.start < campos.config.max) {
                var cloned = this.$el.clone();
                this.$el.after(cloned);
                cloned.find('span').attr('class', 'glyphicon glyphicon-minus-sign');
                cloned.find('a').attr('class', 'remove_button plus-minus');
                this.config.start++;

            } else {

                alert('max ' + campos.config.max + ' inputs');
            }
        },
        removeField: function () {
            console.log($(e.target));
            var $remove = $(e.target).closest(this.$el).remove();
            this.cacheDom();
        }

    }
    campos.init();
})();

2 个答案:

答案 0 :(得分:0)

;(function ( $, window, document, undefined ) {

    // undefined is used here as the undefined global
    // variable in ECMAScript 3 and is mutable (i.e. it can
    // be changed by someone else). undefined isn't really
    // being passed in so we can ensure that its value is
    // truly undefined. In ES5, undefined can no longer be
    // modified.

    // window and document are passed through as local
    // variables rather than as globals, because this (slightly)
    // quickens the resolution process and can be more
    // efficiently minified (especially when both are
    // regularly referenced in your plugin).

    // Create the defaults once
    var campos = "Campos",
        defaults = {

            start: 0,
            max  : 9,

        };

    // The actual plugin constructor
    function Plugin( element, options ) {
        this.element = element;

        // jQuery has an extend method that merges the
        // contents of two or more objects, storing the
        // result in the first object. The first object
        // is generally empty because we don't want to alter
        // the default options for future instances of the plugin
        this.options = $.extend( {}, defaults, options) ;

        this._defaults = defaults;
        this._name = campos;

        this.init();
    }

    Plugin.prototype = {

        init: function() {
            // Place initialization logic here
            // You already have access to the DOM element and
            // the options via the instance, e.g. this.element
            // and this.options
            // you can add more functions like the one below and
            // call them like so: this.yourOtherFunction(this.element, this.options).
            this.cacheDom(this.element,this.options);
            this.bind();
            this.lastChild();
        },

        yourOtherFunction: function(el, options) {
            // some logic
        },
        cacheDom: function(el, options){

            this.$button  = $(el).find(".add_button");              
            this.$remove  =  $(el).find(".remove_button");              
            this.$firstEl = $(el).find(':first');

        },
        bind : function(){
            this.$button.on('click',this.addField.bind(this));
            this.$remove.on('click',this.removeField.bind(this));
        },
        addField: function() {
            this.lastChild();
            if(this.options.start < (this.options.max-1)){

                    var cloned = $(this.element).clone(true);
                    $(this.element).after(cloned);
                    this.options.start++;


            }else{

                alert('max '+ (this.options.max) +' inputs');
            }
        },
        removeField: function(e) {
            console.log(e);
            this.options.start--;
            $(e.target).parent().parent().parent().parent().remove();


        },
        lastChild:function(){
                console.log(this.$remove.length);
            }
    };

    // A really lightweight plugin wrapper around the constructor,
    // preventing against multiple instantiations
    $.fn.campos = function ( options ) {
        return this.each(function () {
            if (!$.data(this, "plugin_" + campos)) {
                $.data(this, "plugin_" + campos,
                new Plugin( this, options ));
            }
        });
    };

})( jQuery, window, document );

答案 1 :(得分:-1)

问题是您没有将e作为函数签名中的参数传递?

 removeField: function (e) {
            console.log($(e.target));
            var $remove = $(e.target).closest(this.$el).remove();
            this.cacheDom();
        }