问题与随机图像脚本在JS
Problems with Random Image Script in JS
我试图获得以下脚本,以替换默认图像随机图像每次页面刷新。总是得到boxID为null错误。为什么boxID为空?
<script type="text/javascript">
function randomThumbs(){
var unalafois=1;
for (unalafois=1; unalafois<9; unalafois++){
boxID=document.getElementById("'unalafois'")
var duh= Math.ceil(Math.random()*8);
boxID.src="thumbs/'+duh+'.jpg";
}}
</script>
下面是HTML代码:
<body onload="randomThumbs()">
<table>
<tr>
<td><img id="1" src="thumbs/1.jpg" /></td>
<td><img id="2" src="thumbs/2.jpg" /></td>
<td><img id="3" src="thumbs/3.jpg" /></td>
<td><img id="4" src="thumbs/4.jpg" /></td>
<td><img id="5" src="thumbs/5.jpg" /></td>
<td><img id="6" src="thumbs/6.jpg" /></td>
<td><img id="7" src="thumbs/7.jpg" /></td>
<td><img id="8" src="thumbs/8.jpg" /></td>
</tr>
</table>
</body>
谢谢!
HTMLElement的ID不能以数字开头。将ID更改为类似img-n的东西,其中n是一个数字。
<body onload="randomThumbs()">
<table>
<tr>
<td><img id="img-1" src="thumbs/1.jpg" /></td>
<td><img id="img-2" src="thumbs/2.jpg" /></td>
<td><img id="img-3" src="thumbs/3.jpg" /></td>
<td><img id="img-4" src="thumbs/4.jpg" /></td>
<td><img id="img-5" src="thumbs/5.jpg" /></td>
<td><img id="img-6" src="thumbs/6.jpg" /></td>
<td><img id="img-7" src="thumbs/7.jpg" /></td>
<td><img id="img-8" src="thumbs/8.jpg" /></td>
</tr>
</table>
然后将脚本改为:
<script type="text/javascript">
function randomThumbs(){
var unalafois=1;
for (unalafois=1; unalafois<9; unalafois++){
//Use var before boxID, just a best practice
var boxID = document.getElementById("img-" + unalafois)
var duh= Math.ceil(Math.random()*8);
boxID.src="thumbs/" + duh + ".jpg";
}
}
</script>
如果您想使用unalafois
作为变量,请删除引号:
boxID=document.getElementById(unalafois)
不要使用以数字开头的id,如果你想符合HTML规范
我明白了!问题是第3行中1周围缺少引号。下面是最后的脚本:
<script type="text/javascript">
function randomThumbs(){
var onecell="1";
for (onecell=1; onecell<9; onecell++){
var picnum=Math.ceil(Math.random()*9);
document.getElementById("img" +onecell).setAttribute("src","thumbs/"+picnum+".jpg");
}}
</script>
相关文章:
- chrome扩展:尽管运行了at:documentidle,js脚本还是过早启动
- 如何在运行时在angular 2中加载外部js脚本
- 为什么我的控制器没有启动函数.js脚本
- 如何让JS脚本在导航后继续运行(谷歌chrome控制台)
- 如何使用Node.js脚本从Rally获取用户的修订历史
- 在Debian中运行包含load()和print()函数的JS脚本
- 更改路由后,运行一次js脚本
- Yii2从js脚本的页面上添加来自供应商文件夹的图像、css、js文件
- PHP和JS脚本的奇怪问题,在我刷新页面之前第一次失败
- js脚本未加载到jinja2模板中
- Disqus的计数.js脚本在索引中无法正常运行.html与react.js网站
- 按顺序异步加载JS脚本(等待上一个脚本完成)
- node.js脚本中出现Sqlite Sqlite_MISUSE错误
- ASP.NET MVC路由-动态加载.js脚本
- 在执行JS脚本后监视对DOM的更改
- 在 Node.Js 脚本中使用 Javascript 计时器在特定时间触发事件
- 合并 2 个 JS 脚本 - 老派
- 简单的拖放JS脚本不起作用
- 从外部 js 脚本创建元素并插入到 html 中
- 将参数传递到外部 JS 脚本的最佳方法