setTimeout函数中的关键字,该函数嵌套在on()方法下.但这并没有奏效

This keyword inside a setTimeout function, which is nested under a on() method. And it is not working

本文关键字:函数 方法 并没有 on 关键字 嵌套 setTimeout      更新时间:2023-09-26
$("ul").on("click", ".start", function() {
    console.log("started");
    var timeInput = $(this).parent().children('.time');
    var timeInputValue = timeInput.val();
    var milliSeconds = Number(timeInputValue)*60*1000;
    console.log(milliSeconds);
    setTimeout(function(){
        alert("Time Over");
        $(this).parent().children('.task').toggleClass("completed");
    }
        , milliSeconds);
})

....................................................................

<ul>
        <li><span class="delete">X</span> <span class="start">S</span> <span class="task">Code ToDo</span></li>
        <li><span class="delete">X</span> <span class="start">S</span> <span class="task">Read two books</span></li>
        <li><span class="delete">X</span> <span class="start">S</span> <span class="task">Run</span></li>       
    </ul>

我知道我在setTimeout函数中错误地使用了this关键字,但我想访问类.task对应于start的元素。

我该怎么做?

alert方法可以工作,但是toggleClass不能工作

你可以用arrow function来做,

setTimeout(() => {
   alert("Time Over");
   $(this).parent().children('.task').toggleClass("completed");
 }, milliSeconds);

如果你在ES5中编写代码,那么使用setTimeout的第三个参数

 setTimeout(function(_this){
   alert("Time Over");
   $(_this).parent().children('.task').toggleClass("completed");
 }, milliSeconds, this);