“document.write()”的问题JavaScript 中的图像数组
我当时尝试使用 document.write()
从我的数组中写入图像。但是它没有显示任何...
// *** Temporal variables
var i = 0;
var j = 0;
var x = 0;
// Create basic linear array
var ImgArray = []
// Do the 2D array for each or the linear array slots
for (i=0; i < 4 ; i++) {
ImgArray[i] = []
}
// Load the images
x = 0;
for(i=0; i < 4 ; i++) {
for(j=0; j < 4 ; j++) {
ImgArray[i][j] = new Image();
ImgArray[i][j] = "Images/" + x + ".jpg";
document.write("<img id= " + x + " img src=ImgArray[i][j] width='120' height='120'/>");
x = x + 1;
}
document.write("<br>");
}
我做错了什么?
Am trying to write using document.write()
an image at the time from my array. However it does not display any...
// *** Temporal variables
var i = 0;
var j = 0;
var x = 0;
// Create basic linear array
var ImgArray = []
// Do the 2D array for each or the linear array slots
for (i=0; i < 4 ; i++) {
ImgArray[i] = []
}
// Load the images
x = 0;
for(i=0; i < 4 ; i++) {
for(j=0; j < 4 ; j++) {
ImgArray[i][j] = new Image();
ImgArray[i][j] = "Images/" + x + ".jpg";
document.write("<img id= " + x + " img src=ImgArray[i][j] width='120' height='120'/>");
x = x + 1;
}
document.write("<br>");
}
What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
看起来你的 JavaScript 不太正确......
Looks like your JavaScript isn't quite right...
看起来您正在尝试使用
new Image()
进行图像预加载,但随后您立即使用document 写出具有相同
,因此图像不会预加载,并且您不会获得任何好处。我还怀疑您在内循环的一行中缺少src
的图像元素.write().src
:生成 HTML 时最好在服务器端完成创建图像元素的循环,但假设这不是一个选项,您可能会完全丢失
ImgArray
变量:It looks like you're trying to do image preloading by using
new Image()
, but then you immediately write out an image element with the samesrc
usingdocument.write()
, so the image will not have preloaded and you get no benefit. I also suspect you're missing a.src
on one line in the inner loop:This looping to create image elements would be best done server-side when generating the HTML, but assuming that's not an option, you could lose the
ImgArray
variable completely:document.write 将任何输入写入脚本元素的位置。尝试这样做:
在脚本的正文中
,将所有输出收集到一个变量,例如 contentVariable,然后
注意:
使用 document.write 甚至 inertml 将元素附加到 dom 是不好的做法。使用 document.createElement 和 element.appendChild 进行 dom 操作。
document.write writes any input the the location of script element. Try this instead:
in body
in your script, gather all output to a variable, say contentVariable, and then
note:
It's bad practice to use document.write and even innertml for appending elements to dom. use document.createElement and element.appendChild for dom manupilation.