【问题标题】:Cloning $(this) in a javascript object?在 javascript 对象中克隆 $(this)?
【发布时间】: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($('&lt;div/&gt;').html($(this).html()))
  • .. 哦,你自己发现了

标签: javascript object call this apply


【解决方案1】:

根据您的需要,调用 self.cloneCard.call($(this)); 而不是 self.cloneCard($(this)); 应该可以。您正在做的是,调用 cloneCard 将发生 clickCard 事件的元素传递给它。

如果这不起作用,我想我们需要更多信息来解决您的问题。

【讨论】:

  • 这也有效,似乎比不使用呼叫要好。另外,现在我知道电话是如何工作的!谢谢。 (对于任何感兴趣的人,它似乎“更好”,因为它不需要传入 $(this) 然后在另一个方法中将其作为变量引用。$(this) 现在是 this 被调用后。太神奇了!
猜你喜欢
  • 2011-01-20
  • 2011-07-18
  • 2013-01-03
  • 2014-01-11
  • 2015-02-08
  • 2014-07-08
  • 2014-10-08
  • 2017-05-22
相关资源
最近更新 更多