Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
173 views
in Technique[技术] by (71.8m points)

javascript - Move Prior Texts In Array Below Latest Text Instead of Being Overwritten

What we have now: So the texts (or sentences) in the array will show every onClick action. The prior texts will be overwritten by the latest texts.

What we want to achieve: Rather than being overwritten, I want all the prior texts to simply move down below the latest texts. Imagine a chat convo where the previous messages simply go down below the latest message in order. I hope it's possible.

What is this for: I want to make like a simple storybook for my little girl. She easily gets overwhelmed by too much words in books and loses interest. I want her to be able to read offline too. So I will definitely appreciate it if we can keep it in vanilla javascript.

This may be easy for most, but I am just like in a primary level right now when it comes to coding. I apologize in advance for my lack of knowledge. But thank you to anyone who can help me.

HTML

<button type="button" id="myBtn">Next</button>
<br><br>
<span id="myText"></span>

Vanilla Javascript

<script>
var texts = [
"text/sentence 1",
"text/sentence 2",
"text/sentence 3",
"text/sentence 4",
"text/sentence 5"
];
var text = document.getElementById("myText");
var btn = document.getElementById("myBtn");
btn.addEventListener("click", changeText);
text.innerHTML = texts[0];


function changeText() {
    var searchTerm = text.innerHTML;
    var index = texts.indexOf(searchTerm) + 1;
    if (index == texts.length) index = 0;
    var result = texts[index];
    text.innerHTML = result;
    return;
}
</script>
question from:https://stackoverflow.com/questions/65898761/move-prior-texts-in-array-below-latest-text-instead-of-being-overwritten

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You may consider a variable which store all the texts which have been read. Thus upon a new text, create the new string with that text to which you concatenate the variable (below named str)

var texts = [
"text/sentence 1",
"text/sentence 2",
"text/sentence 3",
"text/sentence 4",
"text/sentence 5"
];
var text = document.getElementById("myText");
var btn = document.getElementById("myBtn");
btn.addEventListener("click", changeText);
let str = '<p>'+texts[0]+'</p>';
text.innerHTML = str

let index = 1
function changeText() {
  str = '<p>' + texts[index] + '</p>' + str
  myText.innerHTML = str
  index = (index + 1) % texts.length 
}
<button type="button" id="myBtn">Next</button>
<br><br>
<div id="myText"></div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...