通过遍历列表来更改图像的src

时间:2019-12-24 01:00:47

标签: javascript html image src

我正在尝试每十分之一秒更改一次图像。我已经根据其他响应在此处编写了脚本,但仍无法正常工作。这是脚本:

var images = Array();
var index = 0;
images = ["rock.png", "paper.png", "scissors.png"];
var opponent = document.getElementById("opps");

setInterval(myMethod, 100);

function myMethod( ){
    opponent.src = images[index];

    if (index <= 1){
        index++;
    }
    else{
        index = 0;
    }
}

这是标签:

<img src = "" id ="opps"/>

3 个答案:

答案 0 :(得分:1)

您可以执行#include <iostream> #include <type_traits> class Base {}; class ClassA : public Base { public: ClassA(int a, int b) : Base() { std::cout << "ClassA: " << a << " " << b << "\n\n"; } }; class ClassB : public Base { public: ClassB(int a, int b, int c) : Base() { std::cout << "ClassB: " << a << " " << b << " " << c << "\n"; } }; class ClassB0 : public ClassB { public: ClassB0(int a, int b, int c) : ClassB(a, b, c) { std::cout << "ClassB0: " << a << " " << b << " " << c << "\n\n"; } }; class ClassB1 : public ClassB { public: ClassB1(int a, int b, int c) : ClassB(a, b, c) { std::cout << "ClassB1: " << a << " " << b << " " << c << "\n\n"; } }; template <typename T, typename ...Args> T* create(Args&&... args) { T* comp = nullptr; if (std::is_base_of<ClassB, T>::value) { std::cout << "True "; comp = new T(10, std::forward<Args>(args)...); } else { std::cout << "False "; comp = new T(std::forward<Args>(args)...); } return comp; } int main() { create<ClassA>(1, 2); create<ClassB0>(2, 3); create<ClassB1>(2, 3); } 来无限循环遍历数组-当您遍历索引时,它只会回绕

此外,您应该使用index % images.length创建一个空数组。您不必,但这是一个好习惯-Read more

最后,更改图像src的时间通常太短了100毫秒,在大多数情况下,大约1-5秒应该足够了

let a = []
var images = ["rock.png", "paper.png", "scissors.png"];
var index = 0;
var opponent = document.getElementById("opps");

setInterval(myMethod, 100);

function myMethod( ){
    opponent.src = images[index % images.length];
    index += 1;
    
    console.log(opponent.src);
}

答案 1 :(得分:1)

我知道了。对于任何其他出现此错误的人,这是由于您的脚本在html之前运行。在img之后运行脚本。

答案 2 :(得分:0)

您的代码有效,images数组中的字符串是相对的,因此您可能没有在项目中使用它们。我简化了几件事,首先,我在同一表达式中初始化并声明了images数组,其次,我将myMethod()中的if语句变成了三元表达式:

let index = 0
const images = [
  "http://placekitten.com/200/200", 
  "http://placekitten.com/210/210", 
  "http://placekitten.com/220/220"
]

const opponent = document.getElementById("opps");

setInterval(myMethod, 1000)

function myMethod(){
    opponent.src = images[index];

    index = index <= 1 ? index + 1 : 0
}
<img src="" id="opps"/>