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

How to access outside .this in object

我正在尝试将我的功能代码重写为模块模式 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();

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

向事件处理程序传递事件参数。 target 是其有用的属性之一,它是事件发起的 html 元素。请注意,它可能与事件处理程序的 this 不同,后者是事件处理程序附加到的元素,因为事件通过 DOM 向上冒泡。所以如果你有这个 html:

<div id="parent">
  <div id="child"></div>
</div>

然后对于这个 JS 函数:

$("#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();
});

您尝试过:

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

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