如何将内部<script>标记转换为外部Javascript文件? (用于随机图像生成器)

时间:2019-04-21 03:10:57

标签: javascript html random type-conversion generator

我正在尝试将内部HTML脚本元素转换为外部Javascript文件。

在HTML文件中,我已将script元素替换为:

  

并添加了

  
 

到head元素。

在Javascript中,我删除了脚本标签并添加了一个函数,但是我对Javascript还是很陌生,无法弄清楚我还需要添加或更改什么才能使转换正常工作

这是发生故障的Javascript代码:

  window.onload = random_ad;

 函数random_ad(){
     document.getElementById(“ firstads”);
    var total_images = 7;
    var random_number = Math.floor((Math.random()* total_images));
    var random_img = new Array();
    random_img [0] ='  ';
//....1-5为简洁起见此处不包括//
    random_img [6] ='  ';
    document.write(random_img [random_number]);

 }
 

目标是要有一个由外部JavaScript文件随机生成的超链接图像。图像必须足够小以适合放在旁边的列中,但是现在它们是浏览器的大小。非常感谢您提供解决此问题的帮助!

2 个答案:

答案 0 :(得分:1)

同意Tigger。

您在此处使用document.write():
https://www.w3schools.com/jsref/met_doc_write.asp

'write()方法将HTML表达式或JavaScript代码写入文档。'
“ write()方法主要用于测试:如果在HTML文档完全加载之后使用它,它将删除所有现有的HTML。”

document.write()有时可能有用,但通常不是标准做法。 您需要设置innerHTML或附加HTML DOM元素。您可以像这样将其添加到正文的末尾:

#include <ESP8266WiFi.h>
#include <WiFiUdp.h>

const char *ssid = "M3-L7";
const char *password = "mySmartChoice";
unsigned int localPort = 2390; 

WiFiUDP Udp;
void setup() {
    delay(1000);
    Serial.begin(115200);
    WiFi.softAP(ssid, password);
  Udp.begin(localPort);
}

void loop() {
 Udp.beginPacket("192.168.4.1", localPort);
 Udp.write("Hello");
 Udp.endPacket();
 delay(10);
}

您可以使用querySelector,getElementById,getElementsByClassName和其他选择器。我一般建议使用querySelector,例如google:)。

另外,如果您有时间,我建议您检出document.createElement,并附加函数以将元素添加到标签中,而不是通过文本设置innerHTML。以下是不鼓励使用innerHTML的一些答案:
Why is "element.innerHTML+=" bad code?

答案 1 :(得分:0)

您有很多权利,但是您缺少一些小东西。

还有多种不同的方法可以完成此任务。以下内容尽可能接近原始代码。

在HTML <head>元素中,只有很小的变化。

<script defer src="javascript/rec_images.js"></script>

为什么defer胜过async?好吧,that will depend on what you are doing,但是在大多数情况下,并且基于小代码示例,我认为这将是最佳匹配。

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>

编辑:

确定要使用createElementwhich is encouraged。以前曾经innerHTML很懒。