【问题标题】:array in javascript is not working properly, i need t [duplicate]javascript中的数组无法正常工作,我需要[重复]
【发布时间】:2018-03-27 10:24:12
【问题描述】:
<script>
f = new Array();
f.push('h');
f.push('a');
f.push('i');
f.push('l');
f.push('e');
f.push('r');
f.push('i2');
f.push('s');
t = f.length;
face = f[Math.floor(Math.random() * t)];
document.getElementById('img').innerHTML = '<img src="' + face + '.png" alt="something" />';
</script>

它不起作用 我正在尝试创建一个数组来随机化图像并将它们显示给用户,但它不起作用,我不知道为什么

【问题讨论】:

  • 你的 html 是否有一个 id 为 img 的元素?如果有,页面下方是否有这个脚本标签?
  • 您的 javascript 看起来不错。也许你运行得太快了——例如在页面加载之前?尝试将脚本放在结束正文标记之前。
  • 定义“不工作”!我在浏览器控制台中运行了您的 js,并确认它从数组中选择了一个随机值。
  • 我试过了,而且成功了。谢谢
  • 在这段代码运行之前id="img" 是否存在?还有它是什么?提供minimal reproducible example

标签: javascript html arrays image


【解决方案1】:

看来这里的答案是确保代码在页面加载后运行

<body>

...

<script>
  f = new Array();
  f.push('h');
  f.push('a');
  f.push('i');
  f.push('l');
  f.push('e');
  f.push('r');
  f.push('i2');
  f.push('s');
  t = f.length;
  face = f[Math.floor(Math.random() * t)];
  document.getElementById('img').innerHTML = '<img src="' + face + '.png" alt="something" />';
</script>

</body>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-28
    • 1970-01-01
    • 2021-08-10
    相关资源
    最近更新 更多