简体   繁体   English

Javascript问题或比什么都缺乏知识

[英]Javascript problem or more lack of knowledge than anything

Hopefully this is fairly simple.希望这相当简单。

This is my current code below.这是我下面的当前代码。 It is generating a random number for me on loading the page and works fine for the target div.它在加载页面时为我生成一个随机数,并且适用于目标 div。 However, I want this to run this function within 8 separate divs.但是,我希望它在 8 个单独的 div 中运行此功能。 I obviously cannot have 8 divs with the same id so I changed this to getElementByClassName and changed the class on my div to vvv and got rid of the id but for some reason this doesn't work?我显然不能有 8 个具有相同 id 的 div,所以我将其更改为 getElementByClassName 并将我的 div 上的类更改为 vvv 并摆脱了 id 但由于某种原因这不起作用?

Also, do I need anything else in my script to call this function for more than one div?另外,我的脚本中是否需要其他任何内容来为多个 div 调用此函数? Any help much appreciated!非常感谢任何帮助!

<script>
        let text = "VAC";       
        
        window.onload = function ()
        {
        var output = document.getElementById("vvv");
        
        setInterval(function ()
        {
            output.innerHTML = Math.floor(Math.random() * (115 - 105 + 1)) + 105 + " " + text; 
        }, 2000);//this value is the time between generating the number//
        };
</script>

You are looking for getElementsByClassName (not getElementByClassName).您正在寻找 getElementsByClassName(不是 getElementByClassName)。

 let text = "VAC"; let outputs = document.getElementsByClassName("vvv"); let randomDivs = function() { for (let output in outputs) { outputs[output].innerHTML = Math.floor(Math.random() * (115 - 105 + 1)) + 105 + " " + text } } randomDivs() setInterval(randomDivs, 2000); //this value is the time between generating the number//
 <div class="vvv"></div> <div class="vvv"></div> <div class="vvv"></div> <div class="vvv"></div> <div class="vvv"></div> <div class="vvv"></div> <div class="vvv"></div> <div class="vvv"></div>

You may write it like this.你可以这样写。

<body>
    <div class="vvv">1234</div>
    <div class="vvv">1234</div>
    <div class="vvv">1234</div>
    <script>
        let text = "VAC";       
        var output = document.getElementsByClassName("vvv"); //you can use getElementsByTagName("div") as well
        setInterval(function (){
            Array.from(output).forEach((item, index) => {item.innerHTML = Math.floor(Math.random() * (115 - 105 + 1)) + 105 + " " + text;}
        )}, 2000)
    </script>
</body>

Note: Didn't realize it was answered already with similar approach.注意:没有意识到已经用类似的方法回答了它。 You may try getElementsByTagName("div") as well as suggested.您可以按照建议尝试 getElementsByTagName("div") 。 But it has it's limitations too.但它也有它的局限性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM