I searched everywhere on here on an alternative on printing to HTML from a JavaScript function to HTML without using document.write() but document.getElementById() doesn't seem to work and I'm really not sure how to go about doing this.
I have this so far
JavaScript
function trials() {
while (num_trials > 0) {
for (var i = 0; i < random.length; i++) {
document.write(random[i]);
}
}
}
Where "random" is an array of letters
HTML
<div id ="container">
<center>
<i>**TRIALS HERE**</i><br><br>
<font size="8">
<script>trials();</script><br><br>
</font>
</center>
</div>
I'm also looking for a way to hide each letter after each iteration of the for-loop so that it doesn't just print as a long string of letters.
Basic idea is to use an interval to loop through the array so there is a delay. You want to set the text with innerHTML or 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
I would try setting the div to a variable:
var div = $('#container');
function trials() {
while (num_trials > 0) {
for (var i = 0; i < random.length; i++) {
div.appendTo(random[i]);
}
}
HTML
Then maybe hiding the container div (style='display:none;') would prevent the numbers printing out, but still accessible:
<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>
It may be very useful for you to use 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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.