【发布时间】:2014-03-31 17:37:33
【问题描述】:
我正在学习如何使用对象来帮助组织我的代码并赋予它一些结构,但我遇到了一个问题。我不明白如何将一个函数内部的 $(this) 设置为另一个函数的 $(this)。
我正在研究调用和申请,但我似乎无法掌握它在这种情况下的工作原理。
cloneCard 和 clickCard 是我遇到问题的地方。我想将单击卡片时引用的 $(this) 传递给 cloneCard 函数。
到目前为止,这是我的代码(已更新以反映答案):
var Modal = {
init: function(config) {
this.config = config;
this.clickCard();
this.removeModal();
this.clickOutside();
this.createClose();
},
clickCard: function() {
$this = this;
this.config.boardOutput.on('click', '.card', function(event) {
$this.showOverlay();
$this.cloneCard.call($(this));
$this.createClose();
});
},
cloneCard: function() {
this.clone()
.replaceWith($('<div/>').html(this.html()))
.removeClass('card')
.addClass('modal')
.css("margin-top", $(window).scrollTop())
.prependTo('body');
},
showOverlay: function() {
this.config.overlay.show();
},
removeModal: function() {
$('.modal').remove();
$('.overlay').hide();
},
clickOutside: function() {
this.config.overlay.on('click', this.removeModal);
},
createClose: function() {
$('<span class="close">X</span>')
.prependTo('.modal')
.on('click', this.removeModal);
}
};
Modal.init({
boardOutput: $('#board-output'),
overlay: $('.overlay')
});
【问题讨论】:
-
感谢您的回复。显然我做得对,但我忘记在 replaceWith 方法中使用新的 $this 。谢谢!
-
你报告的不是问题。这行是问题
.replaceWith($('<div/>').html($(this).html())) -
.. 哦,你自己发现了
标签: javascript object call this apply