Detailed Explanation of this Points and Custom Attributes in JavaScript

  • 2021-11-14 04:43:49
  • OfStack

Catalog 1. this Keyword 2. Custom Attributes 3. Comprehensive Case 1: Implementation Appendix Summary of tab Tab

1. this keyword

this points to the current element

this in global function points to window object

A global function is declared in the code, which belongs to the browser window object, so this represents the browser window object window


function fn() {
	consolo.log(this);
}
fn()

The this in the tag event property points to the window object

If you call a global function in a tag property, as follows:


<button onclick="fn()"> Click me to try </button>

function fn() {
	console.log(this)
}

this in the event property function points to the label of the current operation

If 1 function is declared on the attribute of the tag object, then this function belongs to the tag attribute, so the this inside the function points to the current tag object


<button id="btn"> Click me to try </button>

var btn = document.getElementById('btn');
btn.onclick = function() {
	console.log(this);
}

2. Custom properties

In the development of front-end web pages, JavaScript syntax is mainly used to operate tag objects. In some specific situations, it is necessary to set custom attributes to operate tags

Basic syntax: element. Attribute name = attribute value


var btn = document.getElementById('btn');
btn.index = 1;

3. Comprehensive Case 1: Implementation of tab tab

Implementation steps
1. Complete the design of static page first (see appendix for html and css codes)

2. Get the page elements first


 var uli = document.querySelector('ul').querySelectorAll('li');
 var oli = document.querySelector('ol').querySelectorAll('li');

3. Add click events to elements through the for loop


for (var i = 0; i < uli.length; i++) {          
            uli[i].addEventListener('click', function () {   
               } )
        }

4. Add custom attributes to elements and index numbers to corresponding tabs


  uli[i].index = i;

Add the corresponding style to the click event (complete code)


for (var i = 0; i < uli.length; i++) {
            uli[i].index = i;
            uli[i].addEventListener('click', function () {
                for (var j = 0; j < uli.length; j++) {
                    uli[j].className = '';
                    oli[j].className = '';
                }
                this.className = 'current';
                oli[this.index].className = 'current';
            })
        }

Note: In this case, the corresponding tabs are displayed and hidden by adding class names. Before adding corresponding class names to elements, the class names of all elements need to be cleared

Appendix


<button onclick="fn()"> Click me to try </button>
0

Summarize

This article is here, I hope to give you help, but also hope that you can pay more attention to this site more content!


Related articles: