背景
我只是给了jQuery一个小时,我无法使用$([selector]).hide([milliseconds])
隐藏一个元素,在我的示例代码中,当我单击该元素时调用该元素,在这种情况下是锚点标记<a>
。但我最终得到了它,但我不明白为什么会这样。我需要使用function
关键字进行的唯一更改,所以:
注意:使用的示例this
不是&#34; a&#34;,请参阅修改
event => {
$(this).hide(2000);
}
进入这个
function(event){
$(this).hide(2000);
}
问题
为什么使用功能并使用&#39;箭头&#39;功能不是吗?两者之间有区别吗?
我的源代码,用于测试:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Demo</title>
<style>
a.test{
font-weight: bold;
}
</style>
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<!--<script src="https://code.jquery.com/jquery-1.10.2.js"></script>-->
</head>
<body>
<a href="http://jquery.com/">jQuery</a>
<script>
// $(document).ready(function () {
// // $("a").click(event => {
// // alert("Thanks for visiting!");
// // //prevents the opening of the link (what are the default events of other events types?)
// // event.preventDefault();
// // //Special Effects - http://api.jquery.com/category/effects/
// // });
// });
$("a").click(function(event){
event.preventDefault();
$( this ).hide(2000);
});
$("a").addClass("test");
</script>
</body>
</html>
答案 0 :(得分:3)
箭头功能不会创建一个绑定到this
的新范围。所以,要解决这个问题,只需使用普通函数(如下图)。或者,您可以在箭头功能中执行$(event.currentTarget).hide(2000);
。
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Demo</title>
<style>
a.test{
font-weight: bold;
}
</style>
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<!--<script src="https://code.jquery.com/jquery-1.10.2.js"></script>-->
</head>
<body>
<a href="http://jquery.com/">jQuery</a>
<script>
$("a").click(function(event) {$(this).hide(2000)});
$("a").addClass("test");
</script>
</body>
</html>