I am looking to pull 5 "random" lines from a text file while not repeating any. Each line from the text file has html code which would be inserted into a side menu. I have read up on the Fisher–Yates shuffle but not sure how to incorporate it in this manner with javascript. Presently I have the following throwing an error:
var request = new XMLHttpRequest();
request.onload = function() {
var i = 0;
// get the file contents
var fileContent = this.responseText;
// split into lines
var fileContentLines = fileContent.split( '\n' );
var target = document.getElementById( 'random-testimonial' );
var targetHTML = target.innerHTML;
while ( i < 5 ) {
// get a random index (line number)
var randomLineIndex = Math.floor( Math.random() * fileContentLines.length );
// extract the value
var randomLine = fileContentLines[ randomLineIndex ];
// add the random line in a div if not duplicate
if ( ! targetHTML.contains(randomLine) ) {
targetHTML += randomLine;
i += 1;
}
}
target.innerHTML = targetHTML;
};
request.open( 'GET', 'content.txt', true );
request.send();
and
<div id="random-content"><script src="content.js"></script></div>
Error:
content.js:19 Uncaught TypeError: targetHTML.contains is not a functionrequest.onload @ content.js:19
Aucun commentaire:
Enregistrer un commentaire