繁体   English   中英

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

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

我正在尝试运行一个脚本,该脚本在声明的秒数后从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错误的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中的this。 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#you-dont-know-js-this--object -原型

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM