[英]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>×</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
也有错字deleteInput: function () { ); ... the rest of the code
deleteInput: function () { ); ... the rest of the code
,请在功能后删除多余的)
。 我建议您尝试$(this.settings)..因为this
得到了Modal,然后您需要访问该对象内的另一个对象,即settings
。 所以您的模态对象由其他对象组成,我在想这种方式您应该可以得到它:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.