图像src在javascript循环中没有变化

时间:2018-01-25 07:50:14

标签: javascript html

function abc(){
    var i = 1;
    while(i<=6){
        var ImageSrc = i + ".png";
        console.log(ImageSrc);
        document.getElementsByName('faceImg')[0].src = ImageSrc;
        i += 1;
    }
}

我正在调用此函数来动态更改图像src。但只显示最后一张图片。循环中的其他图像未显示。

6 个答案:

答案 0 :(得分:3)

假设您尝试以每帧之间的时间间隔显示从1到6的图像:

&#13;
&#13;
let i = 1;

const timeInBetweenFrames = 1000; // Milliseconds
const imageSrc = "http://via.placeholder.com/450x250?text=";
const image = document.getElementsByName('faceImg')[0];

const incrementImage = () => {
  image.src = imageSrc + i;
  console.log(imageSrc + i);

  if (++i <= 6) {
     window.setTimeout(incrementImage, timeInBetweenFrames);
  }
};

incrementImage();
&#13;
<img name="faceImg" />
&#13;
&#13;
&#13;

答案 1 :(得分:1)

更改

document.getElementsByName('faceImg')[0].src = ImageSrc;

document.getElementsByName('faceImg')[i].src = ImageSrc;

答案 2 :(得分:1)

循环将在几分之一秒内执行,因此您只能看到最后一个图像,使用setInterval进行一些延迟更改。

self.client.credentials(HTTP_AUTHORIZATION='Basic {}'.format(credentials.decode('utf-8'))
function abc() {
  var i = 1;
  var img = document.getElementsByName('faceImg')[0];

  // initialize interval and keep reference to clear inerval
  // also keep reference to the callback for calling initially
  var refInt = setInterval(callback = function() {
    // generate source
    var ImageSrc = i + ".png";
    // update source
    img.src = 'http://img.pranavc.in/100?t=' + ImageSrc;

    // clear interval based on when i reached 6
    if (i++ == 6) clearInterval(refInt); // or if (++i == 7)
  // set the delay here
  }, 1000);

  // call the callback for initial image, you can avoid
  // if you don't need to show image on initially
  callback();
}

abc();

使用ES6语法:

<img name=faceImg width=100 height=100>
let i = 1;
const img = document.getElementsByName('faceImg')[0];

const callback = () => {
  img.src = 'http://img.pranavc.in/100?t=' + i + ".png";
  if (i++ === 6) clearInterval(refInt);
}
const refInt = setInterval(callback, 1000);

callback();

答案 3 :(得分:0)

在你的功能中

function abc(){
var i = 1;
while(i<=6){
    var ImageSrc = i + ".png";
    console.log(ImageSrc);
    document.getElementsByName('faceImg')[0].src = ImageSrc;
    i += 1;
    //sleep(1000);
}
//document.getElementsByName('faceImg')[0].src = ImageSrc;
}

您正在将i变量初始化为计数器,但您尚未在此循环中使用它

document.getElementsByName('faceImg')[0].src = ImageSrc;

将此[0]更改为[i]您已初始化的计数器。

document.getElementsByName('faceImg')[i].src = ImageSrc;

答案 4 :(得分:0)

你把所有东西放在索引0上

[0].src = ImageSrc

您需要i代替0作为

 document.getElementsByName('faceImg')[i].src = ImageSrc;

答案 5 :(得分:0)

更改

document.getElementsByName('faceImg')[0].src = ImageSrc;

document.getElementsByName('faceImg')[i].src = ImageSrc;

也可以使用

let ImageSrc = i + ".png"; 

而不是

 var ImageSrc = i + ".png";