2017-05-26 55 views
2

背景JQuery的:使用()=> {}和()函數的語法,後者的作品

我只是給jQuery的一個去了一個小時,我無法掩飾的元素使用$([selector]).hide([milliseconds]),這在我的示例代碼中,當我單擊元素時調用,在這種情況下爲錨定標記<a>。但我最終得到了它,但我不明白爲什麼如此。唯一的變化,我需要使用function關鍵字,而不是做,所以這一點:

注意:實例中使用this不是 「a」,看到編輯

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> 
+0

您是否使用'this'您的箭頭功能中,比如'事件=> $(本).hide(2000)'?如果是這樣,請參閱https://stackoverflow.com/questions/28371982/what-does-this-refer-to-in-arrow-functions-in-es6 –

+1

'function(event)=> { $(「a」 ).hide(2000); }'看起來不對 –

+0

糟糕,是的,我的意思是沒有=>那部分。謝謝 – ManWithAComputor

回答

3

Arrow功能不會產生拴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>

+0

'箭頭函數不會創建一個連接到這個'的新範圍' - 'this'是指當前事件嗎?我認爲這是指選定的元素。 – ManWithAComputor

+0

我現在明白了,箭頭函數並沒有讓他們創建自己的'this'值,而是從它所在函數的作用域繼承它的值。在我的情況下,這指的是使用'Window'對象時箭頭功能。 – ManWithAComputor

相關問題