Canvas Lesson 01

jQuery Library Moved from CDN

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

to local

<script src="jquery-1.12.1.min.js"></script>

Before

    <div class="color">
      色:
      <a href="" class="black" data-color="0, 0, 0, 1"></a>
      <a href="" class="red" data-color="255, 0, 0, 1"></a>
      <a href="" class="blue" data-color="0, 0, 255, 1"></a>
    </div>
    $(".color a").click(function(){
      cnvColor = $(this).data("color");
      console.log("here ");
      return false;
    });

After

    <div class="color">
      色:
      <a class="black" data-color="0, 0, 0, 1"></a>
      <a class="red" data-color="255, 0, 0, 1"></a>
      <a class="blue" data-color="0, 0, 255, 1"></a>
    </div>
	var cElements = document.getElementsByClassName('color');
	for (let i = 0; i < cElements.length; i++) {
		//console.log(cElements[i].className+":"+cElements[i].nodeName);
		console.log(cElements[i].childNodes+":"+cElements[i].nodeName);
		var elms = cElements[i].childNodes;
		for (let j = 0; j < elms.length; j++) {
			console.log("1");
			elms[j].onclick = function() {
				console.log("2");
				cnvColor = this.getAttribute( "data-color" ) ;
			}.bind(elms[j]);
		}
	}

解説

In this example we are changing the color of the brush being used by detecting a click on an element.

In the original example we have a short "$(".color a").click(" function.
What this actually means is "any elements with the class name of 'color' and a tagname of 'a'"
And then when the element is clicked the color is identified with "cnvColor = $(this).data("color");"
In this case this refers to the elements being clicked, but it's not always clear when tracing through a program.

In the fix we mostly clean up the jQuery syntax
We start by finding all of the elements with the class name "color" which returns a list of elements
and then we look through each of those elements for childnodes.
For each of the child nodes we can assume these are intended to set the color, so we attach an onclick event
For the onclick event we want to specifically define what the this reference will be, so we bind it to the element being clicked
Then when the element is clicked, we can call the getAttribute on the child element by referencing this

In this way while it more verbose, the code is more descriptive as to what's going on ahead of time, as opposed to being interpreted at runtime
Without any context we can see that we're getting all of the elements of a class type and assigning an onclick function to be referenced
And specifically which point of reference is being used from within the onclick function