Why we should use "this" in Callback function

原文鏈接:https://youtu.be/mILVrW1GDfI

Refer to the video as follow:

https://youtu.be/mILVrW1GDfI

 

JS code:

var lis = document.querySelectorAll("li");
var i;

for(i = 0; i < lis.length; i++) {
    lis[i].addEventListener("click", function(){
        //call back function is excuted after ALL CODE FINISHED, when click the li
        //at this time, i equal to 3, lis[i] is UNDEFINED
        lis[i].style.color = (this.style.color === "blue" ? "black" : "blue");
    });
}

//set i to 0 after finish code, lis[i] in call back function set to be lis[0]
// i = 0;

 

 

html code:

<!DOCTYPE html>
<html>
<head>
    <title>Why Use This</title>
</head>
<body>

    <ul>
        <li>One</li>
        <li>Two</li>
        <li>Three</li>
    </ul>


    <script type="text/javascript" src="whyUseThis.js"></script>

</body>
</html>

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章