我想改变" text1"到" text2"首先点击并更改" text2" to" text1"第二次单击仅按一个按钮

时间:2016-01-09 11:49:34

标签: javascript



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>
&#13;
&#13;
&#13;

我想改变&#34; text1&#34;到&#34; text2&#34;首先点击并更改&#34; text2&#34; to&#34; text1&#34;只需按一下按钮。

2 个答案:

答案 0 :(得分:0)

您缺少退货声明:

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

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

else

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

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

答案 1 :(得分:0)

您错过了else声明。

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>

相关问题