JavaScript onclick event: Extracting and displaying random text from a data list.
P粉854119263
P粉854119263 2023-09-02 19:44:17
0
1
619
<p>I want a JavaScript function to randomly select a sentence from a list of data in the same file and display it when I click a button with an "onclick" event. I'm looking for the simplest way to implement this functionality. Does anyone have an example? </p> <p>(Just looking around, first time trying JavaScript)</p>
P粉854119263
P粉854119263

reply all(1)
P粉194919082

let dataList =["句子1","句子2","句子3","句子4"]
let div = document.getElementById('asd')
document.getElementsByTagName("button")[0].addEventListener("click",myFunc)

function myFunc(){
   let x = parseInt(Math.random()* dataList.length )
   div.innerHTML = dataList[x]
}
<button>点击我</button>
<div id='asd'></div>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template