简体   繁体   中英

How can I put multiple functions into 1 in Javascript?

I'm trying to use parameters to solve that, but it doesn't work. How could I put those 3 functions into 1? Thanks in advance.

 <.DOCTYPE html> <html> <head></head> <body> <button onclick=showText1()>Show text 1</button> <button onclick=showText2()>Show text 2</button> <button onclick=showText3()>Show text 3</button> <p id="text1"></p> <p id="text2"></p> <p id="text3"></p> <script> function showText1(){ document.getElementById("text1").innerHTML = "This is a sentence;". } function showText2(){ document.getElementById("text2").innerHTML = "This is another sentence;". } function showText3(){ document.getElementById("text3").innerHTML = "This is the third sentence;"; } </script> </body> </html>

Just Pass Parameter to the function and do action based on the function parameter.

 function showText(type){ if(type === 'text1') { document.getElementById(type).innerHTML = "This is a sentence."; } else if(type === "text2") { document.getElementById(type).innerHTML = "This is another sentence."; } else if(type === "text3") { document.getElementById(type).innerHTML = "This is the third sentence."; } }
 <button onclick=showText('text1')>Show text 1</button> <button onclick=showText('text2')>Show text 2</button> <button onclick=showText('text3')>Show text 3</button> <p id="text1"></p> <p id="text2"></p> <p id="text3"></p>

You can add an id to each button according its number, and set the innerText of the corresponding paragraph.

 function showText(e){ let id = e.target.id; let sentence = ""; if(id=="1") sentence = "This is a sentence."; else if(id=="2") sentence = "This is another sentence."; else if(id=="3") sentence = "This is the third sentence."; if(sentence) document.getElementById(`text${id}`).innerHTML = sentence; }
 <!DOCTYPE html> <html> <head></head> <body> <button id="1" onclick="showText(event)">Show text 1</button> <button id="2" onclick="showText(event)">Show text 2</button> <button id="3" onclick="showText(event)">Show text 3</button> <p id="text1"></p> <p id="text2"></p> <p id="text3"></p> </body> </html>

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM