简体   繁体   中英

JavaScript execute for loop but only see results for last element in array

I'm trying to come up with a js snippet for devtools that will automatically add some information within some input tags.

What I've done:

var labels = [
    "navigationStart",
    "unloadEventStart",
    "unloadEventEnd"];

var newRuleXpath = "//div[@class='btn-group dropdown']/button[@class='btn btn-primary']";
var formControlClass = "form-control ng-pristine ng-untouched ng-empty ng-invalid ng-invalid-required";

String.format = function() {
      var s = arguments[0];
      for (var x = 0; x < arguments.length - 1; x++) {       
          var reg = new RegExp("\\{" + x + "\\}", "gm");             
          s = s.replace(reg, arguments[x + 1]);
      }
      return s;
  }


function getElementByXpath(path) {
  return document.evaluate(path, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
}

function wait(ms){
   var start = new Date().getTime();
   var end = start;
   while(end < start + ms) {
     end = new Date().getTime();
  }
}

function addRule(rule) {
        var resource = rule.startsWith("resources");

        if (resource == true){
            var regexp = String.format("<span id='customextraction-{0}'>((?:[0-9]|.)*?)</span>", rule); 
        }

        else {
            var regexp = String.format("<span id='customextraction-perftimings-{0}'>((?:[0-9]|.)*?)</span>", rule); 
        }
        
        getElementByXpath(newRuleXpath).click();

        var elems = document.getElementsByClassName(formControlClass)
    
        elems[0].value = rule
        
        elems[1].value = regexp
}

for (var i = 0; i < labels.length; i++){
    let rule = labels[i]
    addRule(rule)
    wait(500)
}

So, the code works fine but it only affects the last element of the labels array.

Any thoughts?

Its not that its only affecting the last element in the array. its just that its affecting the last element last. You write

var elems = document.getElementsByClassName(formControlClass)
elems[0].value = rule    
elems[1].value = regexp

So every time the loop iterates, it grabs that group of elements, and applies the same elements (the first two, as you've specified getting [0] and [1] ), and applies your rule. Every iteration of your loop is overwriting the last one, as you're referring the the same DOM nodes every time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM