Can these two for loops be simplified?

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");
      }
}
Mar.07,2021

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?

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b38462-2ae44.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b38462-2ae44.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?