Home > Web Front-end > JS Tutorial > body text

Invalid solution to using $(this) in jQuery in js native function_jquery

WBOY
Release: 2016-05-16 18:06:21
Original
1071 people have browsed it

My example today is like this,

Copy code The code is as follows:

$("ul li").hover(function(){
setTimeout(function(){
$(this).addClass("test");
alert("I appeared after 0.3s delay!") //Test
 },300)
})

When running, this yellow part is not executed, and then I popped up $(this) and it turned out to be undefined (actually Already guessed);
Then I didn’t think about it (I’m used to it) and went directly to Baidu to look for it, but I couldn’t find the answer. Then I thought to myself if there was another way, but I didn’t think it was very reasonable. Then I I thought that I couldn't read it inside, but I could read it outside. Then I assigned $(this) to a variable outside setTimeout(). This solves the problem. Haha, it’s quite a speechless question. In fact, I’m not here to talk about how to solve it. I’m talking about this idea. Don’t blindly go to Baidu and Google before solving the problem.
You have to think of a solution yourself. I really can’t think of it. Go Find answers.
Copy code The code is as follows:

$("ul li").hover(function( ){
var oLi = $(this);
setTimeout(function(){
oLi.addClass("test");
alert("I appeared after 0.3s delay!") //Test
 },300)
})
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template