Vote count: 0
Program:
<html>
...
<button class="accordion">Section 1</button>
<div class="panel"> <p> .... </p> </div>
<button class="accordion">Section 2</button>
<div class="panel"> <p> .... </p> </div>
<button class="accordion">Section 3</button>
<div class="panel"> <p> .... </p> </div>
<script>
var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].onclick = function(){
this.classList.toggle("active");
this.nextElementSibling.classList.toggle("show");
}
}
</script>
...
</html>
I am a newbie to javascript. So, I am not able to understand the above javascript code. I expect "this" keyword refers to window object. Because, it is called within anonymous function and also there is no object for that function. But, it refers to the object "HTMLButtonElement". How "this" refers to Button object ?
asked 8 mins ago
3 Answers
Vote count: 1
How "this" refers to Button object ?
Every function has its own scope, its own this reference.
acc[i].onclick = function(){
this.classList.toggle("active");
this.nextElementSibling.classList.toggle("show");
}
This function is an event handler on acc[i] which is a button with class accordion. So, this is pointing to the DOM object pointing towards HTMLButtonElement pointing towards acc[i]
answered 5 mins ago
Vote count: 0
this keyword basically refers to the current object it is playing a role here as a event handler
answered 4 mins ago
Vote count: 0
this refers to current execution context and in your case its button. If you want it to refer to window, keep a reference of it and then use it inside your onClick handler.
If you run the fiddle, you could see the results.
var acc = document.getElementsByClassName("accordion");
var i;
var that = this;
for (i = 0; i < acc.length; i++) {
acc[i].onclick = function(){
alert(this);
alert(that);
this.classList.toggle("active");
this.nextElementSibling.classList.toggle("show");
}
}
https://jsfiddle.net/g1s0r9as/
answered 3 mins ago
برچسب:
نویسنده: استخدام کار
تاريخ: سه
شنبه
11 خرداد
1395 ساعت: 17:53