JS在for循环中创建动态变量

时间:2018-05-29 16:34:27

标签: javascript loops for-loop dynamic

由于某种原因,此for循环中的动态变量不会在函数中更新,而是在控制台中更新。

某人知道为什么会这样吗?非常感谢您的帮助:)!

$(".numberOfImages").on("mousemove change", function(){
  numberOfImages = this.value;
  changeImageNumber();
});

function changeImageNumber(){
  for(var i = 0; i < numberOfImages; i++){
    console.log(numberOfImages);
    images[i] = "img/image" + i + ".jpg";
  }
}

2 个答案:

答案 0 :(得分:0)

它按预期工作,但没有错,而是全局变量,只需将值传递给函数。

&#13;
&#13;
var numberOfImages = 0;
var images = [];
$("#numberOfImages").on("change", function(){
  numberOfImages = this.value;
  changeImageNumber();
  console.log(images)
});

function changeImageNumber(){
  images = [];
  console.log(numberOfImages);
  for(var i = 0; i < numberOfImages; i++){
    images[i] = "img/image" + i + ".jpg";
  }
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select id="numberOfImages">
<option value=1 >1</option>
<option value=2 >2</option>
<option value=3 >3</option>
<option value=4 >4</option>
</select>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

是的,它有点有效。但for循环中numberOfImages的值仍然保持默认值= 0.即使你改变选项..至少在我的情况下..你知道为什么吗?我的整个代码如下所示:

var sliderWidthValue = 1;
var sliderHeightValue = 1;

var distanceLayerWidthValue = 45;
var distanceLayerHeightValue = 45;

var numberOfImages = 10;
var images = [];

$(window).load(function(){
  $("#loadingMessage").hide();
  $("main").show();
});

$(document).ready(function() {

changeImageNumber();

// Change number of images (not working yet)
$(".numberOfImages").on("mousemove change", function(){
  numberOfImages = this.value;
  changeImageNumber();
});

function changeImageNumber(){
  images = [];
  for(var i = 0; i < numberOfImages; i++){
    console.log(numberOfImages);
    images[i] = "img/image" + i + ".jpg";
  }
}

$.each(images, function(i, val) {
    $("<img />")
        .attr("src", val)
        .appendTo("#images")
        .addClass("image"+i);

    $(".image"+i)
        .wrap( "<div class=container"+i+"></div>" );

    containerChange();

    //change container size
    $(".sliderWidth").on("mousemove change", function(){
      sliderWidthValue = this.value;
      containerChange();
    });

    $(".sliderHeight").on("mousemove change", function(){
      sliderHeightValue = this.value;
      containerChange();
    });

    //Change distance between layers
    $(".distanceLayerWidth").on("mousemove change", function(){
      distanceLayerWidthValue = this.value;
      containerChange();
    });
    $(".distanceLayerHeight").on("mousemove change", function(){
      distanceLayerHeightValue = this.value;
      containerChange();
    });

    function containerChange(){
      $(".container"+i)
          .css('width', sliderWidthValue*10+(i*distanceLayerWidthValue) + "px")
          .css('height', sliderHeightValue*10+(i*distanceLayerHeightValue) + "px")
          .css('z-index', i*-1);
    }

});

});