如何在对象中访问外部.this

时间:2018-11-08 15:22:33

标签: javascript jquery dom this module-pattern

我正在尝试将我的功能代码重写为模块模式js,但我遇到了这个问题-当我尝试删除动态创建的输入字段时,我使用jQuery $(this)访问dom元素并删除其父'div”。但这是指Modal对象,而不是我单击的组件。如何解决该问题,而无需进行某些字段计数和创建具有唯一ID的字段,然后在单击时捕获ID并删除该输入字段?

我的模式:

var s,
    Modal = {
        settings: {
            addInputBtn: $("#add-input"),
            inputContainer: $("#modal-input-form"),
            checkBoxesList: $(".check-box"),
            inputFieldsList: $(".form-control"),
            inputFieldsOptionalList: $(".optional-modal"),
            inputHtml: `
                <div class="input-group mb-3 optional-modal">
                    <div class="input-group-prepend">
                        <div class="input-group-text">
                            <input type="checkbox" class="check-box">
                        </div>
                    </div>
                    <input type="text" class="form-control">
                    <button type="button" class="close">
                        <span>&times;</span>
                    </button>
                </div>`
        },
        init: function () {
            s = this.settings;
            this.bindUIActions();
        },

        bindUIActions: function () {
            s.addInputBtn.on("click", () => Modal.addInput());
            s.inputContainer.on("click", ".close", () => Modal.deleteInput());
        },

        addInput: function () {
            s.inputContainer.append(s.inputHtml);
        },

        deleteInput: function () {);
            $(this).parent('div').remove();
        }
    }
    Modal.init();

enter image description here

2 个答案:

答案 0 :(得分:0)

deleteInput: function (e) {);
            $(e.target).parent('div').remove();
        }

事件处理程序被传递一个事件参数。 target是其有用的属性之一,它是事件起源的html元素。请注意,它可能与事件处理程序的this不同,事件处理程序的<div id="parent"> <div id="child"></div> </div> 是事件处理程序所附加的元素,因为事件在DOM中冒泡。因此,如果您有这个html:

$("#parent").on('click', function(e){
  //this will equal <div id="parent"> unless you bind the handler to something else
  //e.target will equal the clicked element:
  //if the user clicked the child, it will equal the child;
  //if the user clicked parent directly, it will equal parent.
  $(e.target).closest('#parent').doSomething();
});

然后使用此JS函数:

{{1}}

答案 1 :(得分:0)

您尝试过:

deleteInput: function () {;
        $(this.settings).parent('div').remove();
}

此外,您在deleteInput: function () { ); ... the rest of the code处有一个错字,请在功能后删除多余的)。我建议您尝试$(this.settings)..,因为this获得了模态,然后您需要访问该对象内的另一个对象settings。因此,您的模态对象由其他对象组成,我在想这种方式您应该可以得到它:)

相关问题