簡體   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