First of all, why do I have this “ strange ” My idea .
It is based on such a scenario : Recently, I have nothing to do to improve a small business demo: music player . There is a function in it ——
Click an item in the list to pop up the music playing box . I used to be “ Add one for each item click event listeners ”. It's bad !
<div id="videob"></div> //js code videob.onclick=function(){ let video=document.
createElement('video') video.setAttribute('src','xxx') video.setAttribute(
'controls','controls') video.style.cssText="width:90%;height:300px" document.
querySelector('body').appendChild(video) }
Later, when I optimized it, I used it instead Event agent
, I have to admit that it's excellent , But I had to change the structure , bring js There's a bunch of them in the middle of the game “MP4 data ”( An array ), Determine which one is currently when the event is triggered , And then get the assignment from the array audio Of
src .

in fact , Under development Web When applied , I use it a lot JavaScript Get information outside of the document , In some cases , We need to use some techniques to deal with this extra information to ensure that it's safe Web
The application can run normally . generally speaking , The trick is nothing more than stuffing extra information into event handlers or abusing it rel Property or class Property to facilitate injection behavior .

Fortunately, ,HTML5 User defined data attributes are introduced : All custom data properties are in the data- Prefix start ,HTML5
The document's validator ignores it during validation . Developers can add custom data attributes to any element , The attribute value can be the metadata of the photo , Latitude and longitude coordinates or the size of the pop-up window .
The best part is that , In almost all browsers , You can use custom data properties , Because we can use it easily JavaScript To get them .

Why set it up onclick Not good
Before starting operation , We have to do it first “ repeat ” A concept :0 level DOM event
. Generally speaking, it means all kinds of things on The event name of the prefix ( such as :onclick,onmouseon,onkeydown), They can exist in <script>
perhaps HTML In the label , There is no event capture and bubbling mechanism !

There is such a scene :Web Application developers, especially beginners, often rely on pop-up windows , In order to display online help information to users , Additional options or other important user interface features .
We can often see the following code in a page :
<a href="#" onclick="window.open('xxx',null,'width=300,height=300');">go to xxx
</a>
It's just that there's a fatal problem with this piece of unimportant code :

* The destination address of the link is not set ! If JavaScript
It's disabled , Then the link will not be able to guide the user to the corresponding page . This is a very serious problem , So much so that we need to solve it immediately . I suggest that developers never omit href attribute , Under no circumstances should it be for you href
Attribute assignment “#”.
* Pay attention to the separation of behavior and content , Just like using linked style sheets to keep style information separate . At the beginning , use onclick It will bring convenience , But imagine that there's something on the page 50
A link , You'll see that then onclick The scene of method out of control . You will only be able to write repetitions over and over again JavaScript
code . If it is through the server-side code to generate browser-side code , So you're increasing JavaScript event .
In order to solve the above problem , We do it for everyone a Link set href, And added different class! To increase “ Elements of the same type ” The identifiability of .
<a href="xxx" class="pop">go to xxx</a> //js code var link=document.querySelector(
'a.pop') link.onclick=function(e){ e.preventDefault(); window.open(this.
getAttribute('href')); }
We haven't prepared for it yet open Set length and width !

Now? , We go back to the same question as at the beginning of the article !

Using custom data properties
When the app is created JavaScript Of Web When applied , The situation just mentioned is quite common . As you can see , It is desirable to store the desired height and width of the window in code , however onclick
This method has many disadvantages . We can change the way to embed attributes on elements . What we need to do now is transform the link into the following form :
<a href="xxx" data-width="600" data-height="400" class="pop">go to xxx</a> var
link=document.querySelector('a.pop') link.onclick=function(e){ e.preventDefault(
); window.open(this.getAttribute('href'),null,"width="+this.getAttribute(
'data-width')+",height="+this.getAttribute('data-height')); }
ok , This example doesn't seem convincing .
But in order for you to really realize that “ The seriousness of the problem ”, I'll take you to optimize the example at the beginning of the article :
<div id="mxc"> <div class="videob" data-uri="./img/1.mp4"></div> <div class=
"videob" data-uri="./img/2.mp4"></div> </div> mxc.addEventListener('click',
function(e){ let target=e.target || e.srcElement; let video=document.
createElement('video') video.setAttribute('src',target.getAttribute('data-uri'))
video.setAttribute('controls','controls') video.style.cssText=
"width:90%;height:300px;margin:0 auto" document.querySelector('body').
appendChild(video) },false)
That's how it works “ real ” It reflects “ The value of agency ”!

2020-09-09 to update
I found something I didn't pay much attention to : In the parent element event e.target
It's direct “ The lowest child element of the child element that currently triggers the event ”, On top of it “ Parent element ” All with will parentNode It's shown in the form of ( On the prototype ).

I want to find a new way of thinking “ Class native album ”, My idea is : What is the total width at the beginning 100vw, Subelement ( Photo album pictures ) with flex array ; When clicking an image preview, a class name will be added to the parent element dynamically , What is the function of this class : Add parent element to ( Leaflet ) The maximum width of the picture is set to 100vw( Child elements are not set wide from beginning to end ). And then in the js According to the length of the child element to calculate its value “ True width ”(
.style.width). And according to the current click is the number of sub elements should be calculated transform What's the offset ?

Its core code :
// Calculates the number of child elements in the parent element that the current click element is == jQuery:index() var child = document.getElementById(
xxx); var index = Array.prototype.indexOf.call(child.parentNode,child);
Other uses “ Custom data properties ” Most of all, it should be 【 Image lazy loading 】 Is there a replacement map in it :
<body> <div class="imgs"> <div> <img src=" Occupation map " data-src=" Real pictures " alt=" caption "> </
div> ... </div> <script> window.onload=function () { var imgs=document.
querySelectorAll('img'); function offset(el){ let top=el.offsetTop while(el.
offsetParent){ el=el.offsetParent top+=el.offsetTop
//scrollTop: Sets or gets the distance between the topmost of the object and the topmost of the visible content in the window } return { top } } function lazyload(
imgs) { var h=window.innerHeight; //innerheight Returns the height of the document display area of the window var s=document.
documentElement.scrollTop || document.body.scrollTop; //document.body.scrollTop
The height of the web page being rolled away for(var i=0;i<imgs.length;i++){ if((h+s)>offset(imgs[i]).top){
// Window document display height + The height of the roll up , Determine whether the position of the picture has been reached , If we get there , To load , And in loading Use a motion map to get the result “ seize a seat ” (function (i) {
setTimeout(function () { var tmp=new Image(); tmp.src=imgs[i].getAttribute(
"data-src"); // Direct access tmp.onload=function () { imgs[i].src=imgs[i].getAttribute(
"data-src"); // If you can't get it directly ( It's not loaded yet ), Just wait until the previous one is loaded } },1300) })(i) } } } lazyload(imgs
); window.onscroll=function () { lazyload(imgs); } } </script> </body>
in fact , We do use it in many places : For example, custom components (vue / Wechat applet ) We can set parameters for it to the values it carries .

expectation
Developers can embed all kinds of information into tags with custom data attributes .
We can use custom data properties to cache the date and time in the page , The date and time are displayed based on the user's time zone . Just put the time in order UTC In the form of HTML
Page , In the client it can be converted to the user's local time .( Mainly cooperate with the browser cache : It is not updated when the page information has not changed )

Technology
©2019-2020 Toolsou All rights reserved,
How to prevent Mac put to sleep ? Tell you 4 This is an effective way be based on C# Students' grades / mis solve element-ui The drop-down box of has a value but cannot be selected Student information management system source code -C language VR,AR and MR The difference between these technologies 【 Data structure and algorithm 6】 Stack implementation of comprehensive calculator utilize python Yes monkey Automatic log analysis Laya Wechat games sub package loading Alibaba enterprise email smtp set up ( practice )【Java Details of knowledge points 3】 Serializable and Deserialize