一个简单的脚本,其超时值取决于元素's属性-jQuery

A simple script with timeout value dependent on value in element's attribute - jQuery

本文关键字:元素 取决于 -jQuery 属性 超时 一个 简单 脚本      更新时间:2023-09-26

我正在尝试运行一个脚本,该脚本在声明的秒数后从DOM中删除一个元素。

脚本应该为多个元素提供服务,这些元素在声明的时间后消失。

要素:

<div class="communique-warning data-closein="2">
You forgot to declare your country!
</div>
<div class="communique-info data-closein="5">
Your action was completed successfully!
</div>

JS:

$('[data-closein]').each(function() {
    var after = $(this).data("closein") + '000';
    console.log('Time to delete: ' + after);
setTimeout(function() {
    $(this).fadeOut('fast');
    console.log('rolled up');
    $(this).remove();
    console.log('removed!');
}, 3000); // <-- time in milliseconds
});

问题:

使用上面的代码,我得到了Uncaught TypeError: Cannot read property 'defaultView' of undefined错误。

  1. this上下文似乎在setTimeout内不起作用。这样做的正确语法是什么?

  2. 我可以用变量after代替setTimeout函数的3000毫秒值吗?

setTimeout调用的函数内的$(this)井引用该函数。您可以简单地在该函数之前为变量指定$(this),然后在setTimeout调用的函数中使用它:

$('[data-closein]').each(function() {
    var after = $(this).data("closein") + '000';
    console.log('Time to delete: ' + after);
    vat $this = $(this);
setTimeout(function() {
    $this.fadeOut('fast');
    console.log('rolled up');
    $this.remove();
    console.log('removed!');
}, 3000); // <-- time in milliseconds
});

问题是setTimeout中的这个。setTimeout中的"this"与最初在每个函数上使用它的位置不同。要修复它,您需要保存它或将它绑定到传递给setTimeout的函数。。

$('[data-closein]').each(function() {
    var after = $(this).data("closein") + '000';
    console.log('Time to delete: ' + after);
    var $dataCloseIn = $(this);
    setTimeout(function() {
        $dataCloseIn.fadeOut('fast');
        console.log('rolled up');
        $dataCloseIn$.remove();
        console.log('removed!');
    }, 3000); // <-- time in milliseconds
    /* or
    var removeDataCloseIn = function() {
        $(this).fadeOut('fast');
        console.log('rolled up');
        $(this).remove();
        console.log('removed!');
    }.bind(this);
    setTimeout(removeDataCloseIn,3000);
    */
 });

点击此处了解更多信息https://github.com/getify/You-Dont-Know-JS/blob/master/this%20&%20object%20prototypes/README.md#你不知道js这个——对象原型