簡體   English   中英

Javascript問題或比什么都缺乏知識

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

希望這相當簡單。

這是我下面的當前代碼。 它在加載頁面時為我生成一個隨機數,並且適用於目標 div。 但是,我希望它在 8 個單獨的 div 中運行此功能。 我顯然不能有 8 個具有相同 id 的 div,所以我將其更改為 getElementByClassName 並將我的 div 上的類更改為 vvv 並擺脫了 id 但由於某種原因這不起作用?

另外,我的腳本中是否需要其他任何內容來為多個 div 調用此函數? 非常感謝任何幫助!

<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>

您正在尋找 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>

你可以這樣寫。

<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>

注意:沒有意識到已經用類似的方法回答了它。 您可以按照建議嘗試 getElementsByTagName("div") 。 但它也有它的局限性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM