Javascript JQuery:使用()=>;{}和function()语法,后者有效
背景 我只是尝试一下jQuery,一个小时内,我无法使用Javascript JQuery:使用()=>;{}和function()语法,后者有效,javascript,jquery,Javascript,Jquery,背景 我只是尝试一下jQuery,一个小时内,我无法使用$([selector])隐藏一个元素。hide([millides]),在我的示例代码中,当我单击元素时调用它,在本例中是锚定标记 //$(文档).ready(函数(){ ////$(“a”)。单击(事件=>{ ////提醒(“感谢访问!”); /////防止打开链接(其他事件类型的默认事件是什么?) ////event.preventDefault(); /////特别效果-http://api.jquery.com/category/
$([selector])隐藏一个元素。hide([millides])
,在我的示例代码中,当我单击元素时调用它,在本例中是锚定标记
//$(文档).ready(函数(){
////$(“a”)。单击(事件=>{
////提醒(“感谢访问!”);
/////防止打开链接(其他事件类型的默认事件是什么?)
////event.preventDefault();
/////特别效果-http://api.jquery.com/category/effects/
// // });
// });
$(“a”)。单击(函数(事件){
event.preventDefault();
$(本).hide(2000年);
});
$(“a”).addClass(“测试”);
箭头函数不会创建绑定到此的新作用域。所以,要解决这个问题,只需使用一个普通函数(如bellow)。或者,您可以执行$(event.currentTarget).hide(2000)代码>在箭头函数中
演示
a、 试验{
字体大小:粗体;
}
$(“a”)。单击(函数(事件){$(this.hide(2000)});
$(“a”).addClass(“测试”);
您是否在箭头函数中使用了this
,例如事件=>$(this).hide(2000)
?如果是这样,请参见function(event)=>{$(“a”).hide(2000);}
这看起来是错误的oops,是的,我的意思是没有该部分的=>。Thanks@le_m是的,我did@ManWithAComputor然后您应该更改代码示例,因为event=>$('a').hide(2000)
可以工作,但在使用时不起作用。此箭头函数不会创建绑定到此的新范围-此是否引用当前事件?我认为这是指所选的元素。我现在明白了,箭头函数不获取它们自己的创建此值,而是从它所在的函数的作用域中继承它的值。在我的例子中,这是指使用箭头函数时的窗口
对象。
event => {
$(this).hide(2000);
}
function(event){
$(this).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>
// $(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>