can I merge
for(i=0;i<oBtn1.length;iPP){
oBtn1[i].onclick=function(){
alert("a");
}
}
for(i=0;i<oSp1.length;iPP){
oSp1[i].onclick=function(){
alert("a");
}
}
can I merge
for(i=0;i<oBtn1.length;iPP){
oBtn1[i].onclick=function(){
alert("a");
}
}
for(i=0;i<oSp1.length;iPP){
oSp1[i].onclick=function(){
alert("a");
}
}
others asked whether it could be merged. What a big pile upstairs said seemed to reveal all the js I had learned over the past few decades. What if the landlord could not use dom123456789 for some ulterior reasons?
var len = Math.max(oBtn1.length,oSp1.length)
for(i=0;i<len;iPP){
if(oBtn1[i]){
oBtn1[i].onclick=function(){
alert('a');
}
}
if(oSp1[i]){
oSp1[i].onclick=function(){
alert('a');
}
}
}
look at your answer, I. Want to know what the subject wants to ask? Add click events to the list?
then use the event delegate to add clicks to the ul or div on the outer layer of the list
document.getElementById('container').addEventListener('click', function(event) {
var target = event.target;
if(target.tagName == 'li'){
alert(target.innerText);
}
} false);
ps:
is really hilarious. It's good to communicate more, huh?
you're talking about dom0-level events that remind me of the bottom of React's synthetic events. He also used event delegation.
1. First of all, this is a dom level 0 event. It is no longer recommended to register in this way
2. For cases where multiple dom elements need to register events of the same type, you can register events for their parent elements, and handle events of child elements during bubbling
use delegate mode. http://api.jquery.com/on/
$( "-sharpdataTable tbody" ).on( "click", "tr", function() {
console.log( $( this ).text() );
});
it is preliminarily concluded from the code that it is a multi-element binding event for the purpose of the building main loop and uses the DOM level 0 event binding method. Here, I first add some instructions to the registration of the non-recommended events mentioned on the first floor, and then make some suggestions for code simplification.
first of all, one of the advantages of level 0 event binding is its good backward compatibility, because the event binding made by mainstream browser vendors before the earliest standard came out is like this, and after the standard comes out, you have to take into account the previous code, so this binding method is also retained. The biggest disadvantage of this binding method is that it is impossible to bind multiple handlers for the same element and the same event, and through W3C event binding, that is, x.addEventListener can specify whether the event processing phase is in the capture phase or in the bubbling phase. To sum up, because level 0 events do not have finer control over the event trigger phase and are not within the W3C standard, they should be considered in use.
for the part of code, I understand that the purpose of merging two loops is to simplify the amount of code and improve performance. In order to improve the performance of the algorithm, you can consider merging the two loops into one loop. When the set length of oBtn1 is equal to the length of oSp1, the single-layer loop can solve the merging problem.
// DOMnodeList
// nodeListDOM
//
for(let i=0, len = oBtn1.length; i<len;iPP){
oBtn1[i].onclick = function(){
alert('a');
}
oSp1[i].onclick = function(){
alert('b');
}
}
when the lengths of two sets are not the same, one idea of a loop is to use the longer length as the number of iterations, and
internally determines which element to bind to based on the current length value.
let lenOfoBtn = oBtns.length;
let lenOfoSp1 = oSp1.length;
let len = Math.max(lenOfBtn, lenOfoSp1);
// Sp1
for(let i=0; i<len;iPP){
oBtn1[i].onclick = function(){
alert('a');
}
if( i < lenBtnOfSp1 ){
oSp1[i].onclick = function(){
alert('b');
}
}
}
in view of the poor foundation of the personal algorithm, if you want to further optimize the performance of the algorithm, the individual does not have a feasible idea for the time being, and may be able to recursively?
of course, in DOM, you can also use the event delegation proposed on the first floor for code and performance optimization.
//
parentOfObtn = Obtn.parentNode;
parentOfoSp1 = oSp1.parentNode
parentOfbtn.addEventListener("click", function( e ){
//
if( e.target == xxx ){
alert("a")
}
}, false)
parentOfoSp1 .addEventListener("click", function( e ){
// ,
if( e.target == xxx ){
alert("b")
}
}, false)
A further step is to delegate the event to the ancestor node shared by sp1 and oBtn, and Little Transparency will answer the question for the first time.
hope it will be helpful to you.
the answer upstairs has already explained how to do it, but we still need to know why we do it, as follows:
generally speaking, dom needs to have event handlers, and we will just set event handlers for it directly. What if a lot of dom need to add event handlers? For example, if we have 100 li, and each li has the same click click event, maybe we will use the for loop method to iterate through all the li, and add events to them, so what is the impact of this?
in JavaScript, the number of event handlers added to the page will directly affect the overall running performance of the page, because you need to constantly interact with dom nodes, and the more times you visit dom, the more times you will redraw and rearrange the browser, which will prolong the interactive ready time of the whole page. This is why one of the main ideas of performance optimization is to reduce DOM operations. If you want to use event delegation, you will put all the operations into the js program, and the operation with dom only needs to interact once, which can greatly reduce the number of interactions with dom and improve performance.
each function is an object, and if it is an object, it will take up memory. The more objects there are, the greater the memory occupancy rate will be, and the worse the natural performance will be (not enough memory, it is a hard wound, ). For example, the above li, will take up 100 memory space. If it is 1000 or 10000, it can only be said to be hehe. If you use event delegation, Then we can only operate on its parent (if there is only one parent), so that we need a memory space is enough, is not a lot of savings, the natural performance will be better.
there is another way to merge
Why not event agents?
Previous: The problem of a java set
Next: Ask the official List if there is a way to display five columns in one row.
The horizontal coordinates of echarts are not specifically marked, and the X coordinates do not have a grid to indicate. Here is a figure that specifies . js * * createChartSix() { this.$http .get(this.$api.dataChart) .then(rsp => { ...
sincerely ask for advice: < hr > I want to use node as the background to build a video streaming server. The front end is similar to Youku VOD. It can record the playback node function, and load the progress bar at any point (starting from the c...
I need to implement in a chained promise function, any function error in the middle terminates the program, and can catch the error function, and then perform different operations according to different error functions. How can the following code be imp...
I would like to ask what is wrong with this code. Thank you for your answers. ...
is doing a question on Niuke.com. I encounter a problem: to achieve the function callIt, after the call meets the following conditions 1, the returned result is the result after calling fn 2, and the call parameter of fn is all the parameters after th...
A timing examination system is triggered if the click event is triggered within 5 seconds, and if it is not triggered, the system marks the correct answer at the end of the countdown. How to implement ...
description: a regular match is given to the content of an input box, and the matching content is the product activation code. looks like this: "0C31-0B81-BB32-3094-0C31-0B81-BB32-3094 " Code: $( -sharplicenseCode ).keyup(function () { le...
1. The custom event triggers the click event of .cpcstartrefresh, but triggers 2 click events each time 2. The code is as follows: window.onmessage = function (e) { create an event object, var myEvent = document.createEvent( Event ); m...
I configured the MIME type of the file with the amr suffix in the apache configuration as application ms-download, Why it is a garbled page when opening a file in amr format using window.open in chrome, while a file in amr format can be successfully dow...
I got a set of data, which is to choose the type of question. How can I tell if I have chosen the right one answera: "Olympic Games " answerb: "Asian Games " answerc: "Paralympic Games " answerd: "University Games " id: "1772 " question: "f...
read a number, such as 521 change this number to 0521 but put it into four div separately, how to realize it? 0 < div > 5 < div > 2 < div > 1 < div > ...
react projects cannot save store? using redux, data index.js ReactDOM.render( <Provider store={store}> <Router > < Provider>, document.getElementById( root )) registerServiceWorker() actions export const SET_USER = ...
how to find all the NA characters in a HMLT page and replace it with "and invalid " with native JS ...
...
suppose there are only a.js and b.js (only two js and nothing else) b.js export A variable is used for a.js can you directly use import and export without using packaging and compilation tools such as webpack or babel can it be achieved with the h...
do the gods have plug-ins for uploading attachments in the mobile version that can also be uploaded more than one? ...
what does the code circled in the following picture mean? ...
I look at a html ui project with items such as: var apiserver = window[ apiserver ]; url = apiserver + "filterUrlController getUrlData"; I searched the whole project and couldn t find the value of window [ apiserver ]. How do you un...
In the vue-cli project, I directly introduced the particls library into index.html, and the related files are placed in the static directory . <div id="particles-js">< div> <script type="text javascript" src="s...
How does the code return only the result after the last asynchronous operation in the for loop is completed as shown in the figure? Please stop by and give me a hand. ...