Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

trying to understand event handler codes in js

Tags:

javascript

<!DOCTYPE HTML>
<html>
<body>
<link type="text/css" rel="stylesheet" href="example.css">
<div class="d1">1  
    <div class="d2">2
        <div class="d3">3 
        </div> 
    </div>
</div>
<script>
var divs = document.getElementsByTagName('div')
for(var i=0; i<divs.length; i++) {
  divs[i].onclick = function(e) {
    e = e || event
    var target = e.target || e.srcElement
    this.style.backgroundColor='yellow'    
    alert("target = "+target.className+", this="+this.className)
    this.style.backgroundColor = ''
  }
}
</script>
</body>
</html>

Above code is from http://javascript.info/tutorial/bubbling-and-capturing

Questions:

  1. divs[i].onclick, divs is htmlcollection, it is not an arrary, how could we use array style:array[i]? for event handler, why we do not put var in front of it(such as var divs[i].onclick)?

  2. e = e || event, why put event here? and why not put var in front of e, is that because e is the global variable?

like image 207
user2507818 Avatar asked Dec 06 '25 15:12

user2507818


1 Answers

divs[i].onclick, divs is htmlcollection, it is not an arrary, how could we use array style?

It's actually a NodeList, which is an "array-like" object, in that it has a length property and the properties you actually care about are numerically keyed.

for event handler, why we do not put var in front of it?

Because you are referencing an element of the NodeList. You do not want to declare a new variable, you want to use an existing reference.

e = e || event, why put event here?

This is to handle old versions of Internet Explorer, where event objects were not passed to handlers but were instead accessible as window.event.

why not put var in front of e, is that because e is the global variable?

No, it's passed into the event handler function as an argument so there's no need to declare it inside the function.

like image 66
James Allardice Avatar answered Dec 08 '25 04:12

James Allardice



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!