可以在此代码中添加3张照片吗?

时间:2017-02-22 20:04:52

标签: javascript html

对于这项任务,我必须得到3张照片,然后按一个按钮循环浏览我需要制作的照片,以便我可以使用我文件中的照片 。每一点帮助:D

#include <stdio.h>

int main() {
    int a[10], n;
    int largest1, largest2, i;

    printf("enter number of elements you want in array");
    scanf("%d", &n);
    printf("enter elements");
    for (i = 0; i < n; i++) {
        scanf("%d", &a[i]);
    }
    largest1 = a[0];
    for (i = 0; i < n; i++) {
        if (a[i] > largest1) {
            largest1 = a[i];
        }
    }
    largest2 = a[0];
    for (i = 1; i < n; i++) {
        if (a[i] > largest2 && a[i] < largest1)
            largest2 = a[i];
    }
    printf("First and second largest number is %d and %d ", largest1, largest2);
}

更新:我修改了我的代码以尝试此处给出的答案之一,但我仍遇到问题:

&#13;
&#13;
<!DOCTYPE html>
<html>
<body>

<img id="light" src="Red.png">

<script>
var list= ['Green.png', 'Yellow.png', 'Red.png']; 
var i = 0;
function lightsCycle() {
    i = i + 1;
    i = i % list.length;
    var light = document.getElementById("light").src = list[i];
}
</script>

<button type = "button" onclick="lightsCycle()">Next Light</button>
</body>
</html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

在您的函数中,您正在递增i,然后立即将该值丢弃到您将i设置为i的模数的下一行以及数组的长度。那条线不是必需的。

您还需要检查i是否位于阵列支持的最高索引号,如果是,请将其重置为0

接下来,行:

var light = document.getElementById("light").src = list[i];

不必要地声明一个名为light的变量,因为你从不在任何地方使用它。

最后,不要使用HTML属性来连接事件处理程序(onclick,onmouseover等):

创建难以阅读和维护的意大利面条代码(混合在同一行的HTML和JavaScript)。 围绕属性值创建全局范围的包装函数,这些函数会改变this绑定,并可能导致函数无法正常工作。 请勿点击 W3C standards for event handling

// Put the correct relative paths to your images back into the array. Here, I'm substituting 
// online images so that you can see the code working properly.
var list= ['https://cdn2.iconfinder.com/data/icons/crystalproject/crystal_project_256x256/apps/daemons.png',
'https://img.clipartfox.com/837fed127e3383c2a61cf08f76a65081_pics-for-stop-light-yellow-clipart-traffic-light-yellow_641-880.png', 
'http://previews.123rf.com/images/blojfo/blojfo1003/blojfo100300021/6559248-Traffic-light-with-red-light-Stock-Photo.jpg']; 

var i = 0;

// Only scan the document one time to get a reference to the image element.
// It's a waste of resources to do it every time the button is clicked
var img = document.getElementById("light");
var btn = document.getElementById("btn")

// Don't use HTML attributes to hook up event handlers (onclick, onmouseover, etc.)
btn.addEventListener("click", lightsCycle);

function lightsCycle() {
    // If i is less than the max index, increment it, otherwise set it to zero
    i = (i < list.length - 1) ? ++i : 0;
    // Set the source of the image element to the next array value
    img.src = list[i];
}
img { width:50px; }
<img id="light" src="https://cdn2.iconfinder.com/data/icons/crystalproject/crystal_project_256x256/apps/daemons.png">
<button type="button" id="btn">Next Light</button>