gpt4 book ai didi

javascript - 单击按钮时从数组中交换图像

转载 作者:行者123 更新时间:2023-11-30 14:54:32 24 4
gpt4 key购买 nike

我在尝试创建一个脚本来更改数组中的图像时遇到了一个小问题。主要目标是在您单击按钮时显示 10 张图片。单击下一步按钮开始混合所有 10 张图片并且不会离开。它应该在没有 jQuery 的情况下完成。感谢您的建议。

HTML

<button value="show" id="Show">Show Images</button>
<button value="swap" id="Swap" onclick="swapimg()">Swap Images</button>
<div id="image"></div>
<ul>
</ul>

JS

var ul = document.querySelector('ul');
var buttons = document.querySelector('#Show');
buttons.addEventListener('click', add);
var img = ["a.jpg","b.jpg","c.jpg","d.jpg","e.jpg","f.jpg","g.jpg","h.jpg","i.jpg","j.jpg"];
function add() {
for(var i=0; i<10; i++) {
var li = document.createElement('li');
var img1 = document.createElement('img');
img1.src=img[i];
ul.appendChild(li);
li.appendChild(img1);
buttons.style.display = "none";
}
}

function swapimg() {
var myImage1 = new Array();
myImage1[1] = "a.jpg";
myImage1[2] = "b.jpg";
myImage1[3] = "c.jpg";
myImage1[4] = "d.jpg";
myImage1[5] = "e.jpg";
myImage1[6] = "f.jpg";
myImage1[7] = "g.jpg";
myImage1[8] = "h.jpg";
myImage1[9] = "i.jpg";
myImage1[10] = "j.jpg";
var random = Math.floor(Math.random() * myImage1.length);
document.getElementById("image").innerHTML = "<img src='"
+ myImage1[random] + "' alt='image'></img>";
}

最佳答案

您可以使用随机函数在每次点击时随机播放,为您提供可用于生成随机图像的随机数组:

function swapimg() {
var random = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].sort(function() {
return .5 - Math.random();
});

ul.innerHTML = "";

for (var i = 0; i < random.length; i++) {
add(random[i]);
}
}

片段:

var ul = document.querySelector('ul');
var buttons = document.querySelector('#Show');
buttons.addEventListener('click', addImg);
var img = ["a.jpg", "b.jpg", "c.jpg", "d.jpg", "e.jpg", "f.jpg", "g.jpg", "h.jpg", "i.jpg", "j.jpg"];


function addImg() {
ul.innerHTML = "";

for (var i = 0; i < 10; i++) {
add(i);
}
}

function add(i) {
var li = document.createElement('li');
var img1 = document.createElement('img');
img1.src = img[i];
img1.alt = img[i];
ul.appendChild(li);
li.appendChild(img1);
buttons.style.display = "none";
}

function swapimg() {
var random = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].sort(function() {
return .5 - Math.random();
});

ul.innerHTML = "";

for (var i = 0; i < random.length; i++) {
add(random[i]);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button value="show" id="Show">Show Images</button>
<button value="swap" id="Swap" onclick="swapimg()">Swap Images</button>
<div id="image"></div>
<ul>
</ul>

关于javascript - 单击按钮时从数组中交换图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47531299/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com