search

Home  >  Q&A  >  body text

JavaScript onclick event: Extracting and displaying random text from a data list.

<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粉854119263P粉854119263450 days ago601

reply all(1)I'll reply

  • P粉194919082

    P粉1949190822023-09-03 00:57:33

    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>

    reply
    0
  • Cancelreply