简体   繁体   中英

Can't understand Javascript eventhandler with for loop code

I'm trying to learn JavaScript and I saw a code to change the css style of a web page depending on the button you press.

I can't understand why or how a for loop indicate witch button was press. Here is the javascript part:

var buttons = document.getElementsByTagName("button");

var len = buttons.length;

for (i = 0; i < len; i++) {
  buttons[i].onclick = function() {
    var className = this.innerHTML.toLowerCase();
      document.body.className = className;
  };
}

http://jsfiddle.net/qp9jwwq6/

I looked on the net and w3 school but they don't explain that code with a for loop. Can someone explain it to me?

Thank you

Lets break it down.

First we need to have access to the DOM element on the page, so we do that by using a method on the document itself which will return the element we want to manipulate.

var buttons = document.getElementsByTagName("button");

The buttons var will be a list of ALL the buttons on the page. We want to do something with all of them, so first we cache the length of the list, ie, count how many buttons we have.

var len = buttons.length;

Then we basically say: set i to 0, and step it up one until its equal to the number of buttons we have.

for (i = 0; i < len; i++) {

Now, to access one button from the list, we need to use the brackets notation. So buttons[0] is the first element, buttons[1] is the second, etc. Since i starts at 0, we put i in the brackets so that on each iteration it will access the next button in the list.

  buttons[i].onclick = function() {
    var className = this.innerHTML.toLowerCase();
      document.body.className = className;
  };
}

This is equivalent of doing:

 buttons[0].onclick = function() {
    var className = this.innerHTML.toLowerCase();
      document.body.className = className;
  };

 buttons[1].onclick = function() {
    var className = this.innerHTML.toLowerCase();
      document.body.className = className;
  };

 buttons[2].onclick = function() {
    var className = this.innerHTML.toLowerCase();
      document.body.className = className;
  };

// etc.

But of course that is super inefficient, and we may not know how many buttons the page has. So we get all the buttons there, find out how many there are, then go through each button and assign an event handler to it along with a new class.

Now, looking at the onclick handler itself we can see that it first finds the HTML within the button being clicked, turns it into lowercase letters, and assigns it to a variable:

var className = this.innerHTML.toLowerCase();

By using this we're ensuring that each button will know to get it's own innerHTML when clicked. We're not tracking which button is which, we're just telling each button to check it's own content.

Then what it does is change the class of the body HTML element to whatever it is that we just parsed

document.body.className = className;

So say you have something like

<button>success</button>
<button>failure</button>
<button>warning</button>

Clicking the first button would set the <body> element's class to success , clicking the second would set it to failure , and the third would set it to warning .

First line saves all buttons in a variable called buttons. This is actually an array since there can be several buttons on the page. Then you iterate through each button and define a function which should be executed onclick. Lets say you have 2 buttons then it will be buttons[0] and buttons[1] which get the function.

Firstly, speaking generally, the underlying basis for this code is a little wonky and unusual and non-robust, so don't anticipate that you're on the brink of learning any powerful insight into JavaScript or code design.

On to the answer:

The for-loop does not "indicate" which button was pressed. Rather, it loops through every button element on the page and assigns the exact same function definition to the onclick attribute of each element. The code that ends up running when a particular button element is clicked (here I'm talking about the function body) assigns a CSS class to the body element by assigning to document.body.className .

Your question is asking how the function knows which class name to assign to document.body.className . The function grabs the class name from the innerHTML of the button element, which is accessible as this.innerHTML (because in an event handler, this is a reference to the element on which the triggering event occurred). The HTML <button> element is a little bit special, in that, although it is generally a simple-looking button, it is also a non-leaf node, meaning it contains its own HTML. You can put a lot of things in there, but in this example, they just have a plain text node which consists of exactly (or nearly exactly) the class name ( Normal for one and Changed for the other). That's how the function can get a CSS class name that is specific to that button; it grabs it from the text inside the clicked <button> element.

I said "nearly exactly" back there because there's actually a letter-case difference between the button text and the actual CSS classes they've defined in the CSS rules (which are normal and changed ). That's why they have to lower the letter-case of the extracted button text ( toLowerCase() ) before assigning the class name. CSS classes are case-sensitive (see Are CSS selectors case-sensitive? ).

As I said, this is unusual code. It is rather inadvisable to create a mapping (especially an inexact mapping!) between plain HTML text and code metadata (CSS classes in this case).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM