<!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:
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)?
e = e || event, why put event here? and why not put var in front of e, is that because e is the global variable?
divs[i].onclick,divsis 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
varin 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 becauseeis 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With