组合两个具有相似属性的for循环

时间:2015-05-22 19:24:35

标签: javascript loops dom conditional

我有两个div,用数字表示窗口屏幕的宽度和高度,从每100个像素算起。数值包含在span标记内,并通过两个循环插入到它们各自的div容器中。由于这两个循环共享几乎相同的精确方法和条件逻辑,我想知道是否有一种方法可以将它们以某种方式组合起来:

HTML

<div class="rule rule--horizontal"></div>
<div class="rule rule--vertical"></div>

JS

document.addEventListener("DOMContentLoaded", function() {
  var horizontal = document.getElementsByClassName("rule--horizontal")[0],
      vertical   = document.getElementsByClassName("rule--vertical")[0];

  for (var i = 50, screenWidth = screen.width; i < screenWidth; i+= 50) {
    if (i % 100 === 0) {
      horizontal.innerHTML += "<span class='num num--visible'>" + i + "</span>";
    }
  }

  for (var i = 50, screenHeight = screen.height; i < screenHeight; i+= 50) {
    if (i % 100 === 0) {
      vertical.innerHTML += "<span class='num num--visible'>" + i + "</span>";
    }
  }
});

JSFiddle

3 个答案:

答案 0 :(得分:3)

这会产生相同的结果

document.addEventListener("DOMContentLoaded", function() {
    var horizontal = document.getElementsByClassName("rule--horizontal")[0],
        vertical   = document.getElementsByClassName("rule--vertical")[0];
    var a = screen.width > screen.height ? screen.width : screen.height;
    for (var i = 50; i < a; i+= 50) {
        if (i % 100 === 0) {
            if(i < screen.width)horizontal.innerHTML += "<span class='num num--visible'>" + i + "</span>";
            if(i < screen.height)vertical.innerHTML += "<span class='num num--visible'>" + i + "</span>";
        }
    }
});

答案 1 :(得分:1)

您可以创建功能并在两个地方使用它:

document.addEventListener("DOMContentLoaded", function() {
  var horizontal = document.getElementsByClassName("rule--horizontal")[0],
      vertical   = document.getElementsByClassName("rule--vertical")[0];
  loop(horizontal, screen.width);
  loop(vertical, screen.height);

});
function loop(element, max) {
  for (var i = 50; i < max; i+= 50) {
    if (i % 100 === 0) {
      element.innerHTML += "<span class='num num--visible'>" + i + "</span>";
    }
  }
}

答案 2 :(得分:1)

你可以将if语句分解为if(i%100 === 0)这在100,200等上是真的。只需从100开始i并增加100

document.addEventListener("DOMContentLoaded", function() {
   var horizontal = document.getElementsByClassName("rule--horizontal")[0],
       vertical   = document.getElementsByClassName("rule--vertical")[0];

   var createDivs = function (axis, maxSize) {
       for (var i = 100; i < maxSize; i += 100) {
           axis.innerHTML += "<span class='num num--visible'>" + i + "</span>";
       }
   };

   createDivs(horizontal, screen.width);
   createDivs(vertical, screen.height);
});