无法遍历数组;每个项目单独工作

时间:2018-10-25 18:11:54

标签: javascript jquery arrays loops

下面的代码按预期工作:

var slctr = "What's new";
var section = document.querySelector('[aria-label="'+slctr +'"]');
var sectionAs = section.querySelectorAll('a');
$(sectionAs).click(function(e){
    e.preventDefault();
    var t = $(e.target).text();
    var sectionTitle = section.getAttribute('aria-label');
    alert('Title: ' + sectionTitle+', text: ' + t);
    return false;
});

如果我尝试将其应用于每个{{section}},则工作停止:

var sections = [
    "What's new",
    "What's newish",
    "What's not new at all"
    ];

for(var l = 0; l < sections.length; l++){
    var slctr = sections[i];
    var section = document.querySelector('[aria-label="'+slctr +'"]');
    var sectionAs = section.querySelectorAll('a');
    $(sectionAs).click(function(e){
        e.preventDefault();
        var t = $(e.target).text();
        var sectionTitle = section.getAttribute('aria-label');
        alert('Title: ' + sectionTitle + ', text: ' + t);
        return false;
    });
}

为什么循环不起作用?

2 个答案:

答案 0 :(得分:0)

您使用l作为循环变量,但随后尝试访问节[i],并且未定义i

var slctr = sections[l];

答案 1 :(得分:0)

在设置一些事件处理程序时,您需要使用闭包或IIFE,它们有时是异步的。您只需要像这样更新代码即可:

var sections = [
  "What's new",
  "What's newish",
  "What's not new at all"
];

for (var i = 0; i < sections.length; i++) {
  (function (i) {
    var slctr = sections[i];
    var section = document.querySelector('[aria-label="' + slctr + '"]');
    var sectionAs = section.querySelectorAll('a');
    $(sectionAs).click(function(e) {
      e.preventDefault();
      var t = $(e.target).text();
      var sectionTitle = section.getAttribute('aria-label');
      alert('Title: ' + sectionTitle + ', text: ' + t);
      return false;
    });
  })(i);
}

还有一件事是,您使用i作为索引,使用l作为循环。