【问题标题】:Remove THIS element after change it's class更改其类后删除此元素
【发布时间】:2019-08-29 20:18:33
【问题描述】:

我正在尝试在更改其类后 500 毫秒删除元素“this”,但它不起作用

     $('.card').click(function() {
            setTimeout(function(){
                $(this).remove();
                console.log('removed');
            },500);
            $(this).toggleClass("card card-used");
     });

和 HTML

<div class="card">asdasd</div>

我可以在控制台日志中看到“已删除”,但不是 remove()

【问题讨论】:

  • this 存在于 click 函数中,而不是您传递给 setTimeout 的函数中。
  • 为了扩展我上面的评论,this ion 你的例子是指窗口对象

标签: jquery html


【解决方案1】:

为了达到预期的效果,使用箭头函数从父作用域(即.card)继承this,因为setTimeout函数中的this引用了window对象

更多详情请参考此链接-Lexical Scope in JavaScript

$('.card').click(function() {
            setTimeout(() => {
                $(this).remove();
                console.log('removed');
            },500);
            $(this).toggleClass("card card-used");
     });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="card">asdasd</div>

【讨论】:

    【解决方案2】:

    如前所述,this 属于click 上下文,无法在回调中访问。但是你可以将它存储到一个变量中并在回调中访问它。

    $('.card').click(function() {
            var self = this;
            setTimeout(function(){
                $(self).remove();
                console.log('removed');
            },500);
            $(this).toggleClass("card card-used");
     });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-07
      • 1970-01-01
      • 1970-01-01
      • 2018-01-11
      • 2021-03-25
      • 2017-04-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多