简体   繁体   中英

i want to change “text1” to “text2” first click and change “text2” to “text1” second click by only single button

 function fun(){ var read1 = document.getElementById("ddr"); if(read1.innerHTML == "text2"){ read1.innerHTML = "text1"; } read1.innerHTML = "text2" } 
 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body> <button id="bt" onclick="fun()"> button </button> <p id="ddr"> text1 </p> </body> </html> 

i want to change "text1" to "text2" first click and change "text2" to "text1" second click by only single button.

You are missing return statement:

function fun(){
  var read1 = document.getElementById("ddr");

  if(read1.innerHTML == "text2"){
    read1.innerHTML = "text1";
    return; //return here
  }
  read1.innerHTML = "text2"
}

or with else :

function fun(){
  var read1 = document.getElementById("ddr");

  if(read1.innerHTML == "text2"){
    read1.innerHTML = "text1";
  } else {
    read1.innerHTML = "text2"
  }
}

You just missed the else statement.

 function fun(){ var read1 = document.getElementById("ddr"); if(read1.innerHTML == "text2"){ read1.innerHTML = "text1"; } else{ read1.innerHTML = "text2" } } 
 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body> <button id="bt" onclick="fun()"> button </button> <p id="ddr"> text1 </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