gpt4 book ai didi

javascript - jquery: "$(this)"到底是什么意思?

转载 作者:可可西里 更新时间:2023-11-01 01:21:59 25 4
gpt4 key购买 nike

我有一个程序并且运行良好。参见 HERE .

这是代码:

<div id="round"></div>

<style>
#round{
position: absolute;
width: 200px;
height: 200px;
border-radius: 50%;
left: 400px;
top: 200px;
background-color: #e1e1e1;
}
</style>

<script src="jquery.js"></script>
<script src="jquery.easing.1.3.js"></script>
<script>
$(document).ready(function(){
$("#round").click(function(){
setInterval(function(){
$("#round").animate(
{height: 250,
width: 150,
top:150,
left: 425},
{duration: 300}
).
animate(
{height: 200,
width: 200,
top:200,
left: 400},
{duration: 300}
);
}, 0);
});
});
</script>

但是当我将“#round”更改为“this”时。它不会工作。为什么?(其实是可以的,但是当我把它们放到setInterval()里面的时候,就不行了)

$(document).ready(function(){
$("#round").click(function(){
setInterval(function(){
$("#round").animate(
{height: 250,
width: 150,
top:150,
left: 425},
{duration: 300}
).
animate(
{height: 200,
width: 200,
top:200,
left: 400},
{duration: 300}
);
}, 0);
});
});

改成“this”,不行。

$(document).ready(function(){
$("#round").click(function(){
setInterval(function(){
$(this).animate(
{height: 250,
width: 150,
top:150,
left: 425},
{duration: 300}
).
animate(
{height: 200,
width: 200,
top:200,
left: 400},
{duration: 300}
);
}, 0);
});
});

最佳答案

this 是对调用当前函数的成员的引用...

然后您可以将它包装在 jquery 函数 $() 中以像选择另一个选择器一样选择它。

所以 setInterval 调用了一个匿名函数,所以它不会被可引用成员调用,所以它默认为 window 对象。

this 上下文保存在一个变量中,然后像这样在内部使用它......

$(document).ready(function(){
$("#round").click(function(){
var clicked = this; //<----store the click context outside setInterval
setInterval(function(){
$(clicked).animate( //<----------use it here
{height: 250,
width: 150,
top:150,
left: 425},
{duration: 300}
).
animate(
{height: 200,
width: 200,
top:200,
left: 400},
{duration: 300}
);
}, 0);
});
});

关于javascript - jquery: "$(this)"到底是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6749634/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com