javascript - This keyword inside a setTimeout function, which is nested under a on() method. And it is not working -
this question has answer here:
$("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 2 books</span></li> <li><span class="delete">x</span> <span class="start">s</span> <span class="task">run</span></li> </ul>
i know using this
keyword wrong inside settimeout function, want access,the element class .task
respective start
.
how do that?
the alert method working, toggleclass not working.
you use arrow function
that,
settimeout(() => { alert("time over"); $(this).parent().children('.task').toggleclass("completed"); }, milliseconds);
if writing code in es5 use 3rd parameter of settimeout
,
settimeout(function(_this){ alert("time over"); $(_this).parent().children('.task').toggleclass("completed"); }, milliseconds, this);
Comments
Post a Comment