在没有 document.write() 的情况下从 JavaScript 函数打印到 HTML

Print from JavaScript function to HTML without document.write()

我在这里到处搜索了从 JavaScript 函数打印到 HTML 到 HTML 的替代方法,而不使用 document.write() 但 document.getElementById () 似乎不起作用,我真的不知道该怎么做。

目前我有这个

JavaScript

function trials() {

    while (num_trials > 0) {

        for (var i = 0; i < random.length; i++) {
            document.write(random[i]);
        } 
    }
}

其中 "random" 是字母数组

HTML

    <div id ="container">
    <center>
        <i>**TRIALS HERE**</i><br><br>
        <font size="8">
        <script>trials();</script><br><br>
        </font> 
    </center>
</div>

我也在寻找一种方法来在 for 循环的每次迭代后隐藏每个字母,这样它就不会只打印为一长串字母。

使用JQuery可能对您非常有用。

function trials() {

    while (num_trials > 0) {

        for (var i = 0; i < random.length; i++) {
            $('#iToWrite').html( $('#iToWrite').html() + random[i]);
        } 
    }
}
<div id ="container">
    <center>
        <i id='iToWrite'>**TRIALS HERE**</i><br><br>
        <font size="8">
        <script>trials();</script><br><br>
        </font> 
    </center>
</div>

基本思路是用一个区间循环遍历数组,所以会有延迟。您想使用 innerHTML 或 textContent 设置文本。

(function() {

    var outputElem = document.getElementById("outputSpot"),  //where to output the letter on the screen
        current = 0,  //start index in the array
        randomChars = ["W","E","L","C","O","M","E","!"],  //characters to show
        timer = window.setInterval(  //this is how we will loop with an interval
            function () {
                var letter = randomChars[current];  //get next letter
                if (letter) {  //if there is no letter, it will be undefined and we will be done
                    outputElem.innerHTML = letter;  //show the letter to the user
                    current++;  //update the index
                } else {
                    window.clearInterval(timer);  //cancel the timer since we ran out of things to display
                }
            }
        ,1000);  //number of seconds to wait between iterations

}());
<span id="outputSpot">Hello!</span>

Javascript

我会尝试将 div 设置为一个变量:

var div = $('#container');
function trials() {
    while (num_trials > 0) {

        for (var i = 0; i < random.length; i++) {
            div.appendTo(random[i]);
    } 
}

HTML

那么也许隐藏容器 div (style='display:none;') 会阻止数字打印出来,但仍然可以访问:

<div>
    <center>
        <i>**TRIALS HERE**</i><br><br>
        <font size="8">
        <script>trials();</script>
        <div id="container" style="display:none;"></div><br><br>
        </font> 
    </center>
</div>