【发布时间】:2018-06-09 10:03:43
【问题描述】:
我使用 HTML 和 Javascript 开发了以下代码块,功能齐全:
<html>
<body>
<img id="img0" style="position:fixed; width:116px; height:100px;" >
<img id="img1" style="position:fixed; width:116px; height:100px;" >
<img id="img2" style="position:fixed; width:116px; height:100px;" >
<img id="img3" style="position:fixed; width:116px; height:100px;" >
<script>
let rightArray = [300, 213, 387, 300 ];
let bottomArray = [300, 350, 350, 200];
let imageArray = ['image1.png', 'image2.png', 'image3.png', 'image4.png'];
const img0 = document.querySelector('#img0');
img0.style.right = rightArray[0] + "px";
img0.style.bottom = bottomArray[0] + "px";
img0.src = imageArray[0];
const img1 = document.querySelector('#img1');
img1.style.right = rightArray[1] + "px";
img1.style.bottom = bottomArray[1] + "px";
img1.src = imageArray[1];
const img2 = document.querySelector('#img2');
img2.style.right = rightArray[2] + "px";
img2.style.bottom = bottomArray[2] + "px";
img2.src = imageArray[2];
const img3 = document.querySelector('#img3');
img3.style.right = rightArray[3] + "px";
img3.style.bottom = bottomArray[3] + "px";
img3.src = imageArray[3];
</script>
</body>
</html>
正如我们在代码中看到的,一切都非常重复,将这段代码放在循环中会更方便。但我需要一种方法将img tag 放入循环中以执行此操作。我想做的伪代码是这样的:
<html>
<body>
for(let i=0; i<4; i++)
{
<img id="img[i]" style="position:fixed; width:116px; height:100px;" >
}
<script>
let rightArray = [300, 213, 387, 300 ];
let bottomArray = [300, 350, 350, 200];
let imageArray = ['image1.png', 'image2.png', 'image3.png', 'image4.png'];
let objectNameArray = ['img0', 'img1', 'img2', 'img3'];
for(let i=0; i<4; i++)
{
const objectNameArray[i] = document.querySelector('#' + objectNameArray[i]);
objectNameArray[i].style.right = rightArray[i] + "px";
objectNameArray[i].style.bottom = bottomArray[i] + "px";
objectNameArray[i].src = imageArray[i];
}
</script>
</body>
</html>
我 100% 确定最后一个代码不起作用,第一个循环完全错误,第二个循环我们不能像我在那里那样声明和使用对象。所以,基本上我在这里有两个疑问:
- 是否可以将 img 标签放在一个循环中,这样我在使用 Javascript 处理它的参数时就不需要多次复制它?
- 是否可以声明和使用通过循环交互创建的不同对象?
这些问题出现在我的脑海中只是因为我想优化我在这里发布的第一个代码块......我不确定我想要做的事情是否可行,或者我是否正在尝试这样做正确的方式。所以我对以不同方式做同一件事的不同观点持开放态度。 谢谢!!
【问题讨论】:
-
可以直接循环
document.querySelector("img")
标签: javascript html object