Javascript 从数组中选择一个随机元素并检查其索引
我已经记下了这个问题的第一部分,我可以像这样从数组中选择一个随机元素Javascript 从数组中选择一个随机元素并检查其索引,javascript,arrays,random,Javascript,Arrays,Random,我已经记下了这个问题的第一部分,我可以像这样从数组中选择一个随机元素 function setImage() { var images = ['anemone.gif', 'ball.gif', 'crab.gif', 'fish2.gif', 'gull.gif', 'jellyfish.gif', 'moon.gif', 'sail.gif', 'shell.gif', 'snail.gif', 'sun.gif', 'sunnies.gif', 'whale.gif']; var sl
function setImage()
{
var images = ['anemone.gif', 'ball.gif', 'crab.gif', 'fish2.gif', 'gull.gif', 'jellyfish.gif', 'moon.gif', 'sail.gif', 'shell.gif', 'snail.gif', 'sun.gif', 'sunnies.gif', 'whale.gif'];
var slots = [document.getElementById('slot0'), document.getElementById('slot1'), document.getElementById('slot2')];
document.getElementById('slot0').src = images[Math.floor(Math.random() * images.length)];
document.getElementById('slot1').src = images[Math.floor(Math.random() * images.length)];
document.getElementById('slot2').src = images[Math.floor(Math.random() * images.length)];
alert(images.indexOf(document.getElementById('slot2')));
}
但是,第二行没有给我元素的正确索引,我不知道如何找到它?你的意思是:
alert(images.indexOf(document.getElementById('slot2').src));
你为什么不把随机索引设置成一个变量并使用它呢
function setImage()
{
var images = ['anemone.gif', 'ball.gif', 'crab.gif', 'fish2.gif', 'gull.gif', 'jellyfish.gif', 'moon.gif', 'sail.gif', 'shell.gif', 'snail.gif', 'sun.gif','sunnies.gif', 'whale.gif'];
var slots = [document.getElementById('slot0'), document.getElementById('slot1'), document.getElementById('slot2')];
var rnd0 = Math.floor(Math.random() * images.length);
var rnd1 = Math.floor(Math.random() * images.length);
var rnd2 = Math.floor(Math.random() * images.length);
document.getElementById('slot0').src = images[rnd0];
document.getElementById('slot1').src = images[rnd1];
document.getElementById('slot2').src = images[rnd2];
alert(rnd2);
}
如果有,您应该尝试通知图像源,并确保其格式与图像数组匹配
如果您仍然有问题,请使用html和JS设置一个JSFIDLE,这样我们就可以看到发生了什么。
document.getElementById('slot2')
将为您管理节点(img
)。因此,在包含src
值的数组中找不到该值
document.getElementById('slot2').src
将提供完整路径(如http://....../file.ext
),而不仅仅是文件名
使用属性
document.getElementById('slot2')。attributes[“src”]
在slot2
中设置索引,但是在slot0
中设置警报内容是否正确?还有另外两个插槽(slot0,slot1)也需要相同的处理,警报代码在所有三个实例中都给我-1作为数组元素的索引。您可能应该发布更多代码。阵列图像中有什么?如果其中没有ID属性为“slot0”的图像元素,您将无法找到它:)请尝试使用alert(images.indexOf(document.getElementById('slot2').src));如果您早些时候在id设置为“slot0”的情况下尝试,它肯定会失败:)