您有很多权利,但是您缺少一些小东西。
您还可以通过多种不同的方式来完成此任务。 以下内容尽可能接近您的原始代码。
在HTML <head>
元素中,进行了非常小的更改。
<script defer src="javascript/rec_images.js"></script>
为什么要defer
async
? 好吧, 这将取决于您的工作 ,但是在大多数情况下,并根据小的代码样本,我认为这将是最佳的选择。
在javascript/rec_images.js
,进行了一些更改。
/*
Pass the div id to the function to add the image.
*/
function random_ad(divId) {
var random_img = [
{link:"http://www.antares-sellier.com/en/",
image:"javascript/js_images/antares.jpg"},
// add as many as you want
{link:"http://www.scesports.org/",
image:"javascript/js_images/sces.jpg"}
];
var random_number = Math.floor((Math.random()*random_img.length));
var d = document.getElementById(divId);
// always best to check the element was found.
if (d) {
var a = document.createElement("a");
var i = document.createElement("img");
a.setAttribute("href",random_img[random_number].link);
i.setAttribute("src",random_img[random_number].image);
a.appendChild(i);
d.appendChild(a);
}
}
返回HTML
,在<div id="firstads"></div>
,在底部</body></html>
之前的底部,添加以下内容:
<script>
window.onload = function() {
// pass the div id to the function
random_ad("firstads");
}
</script>
</body>
</html>
编辑:
更改为使用createElement
, 这是肯定的做法 。 以前使用innerHTML
很懒。