使用纯JavaScript按钮来回更改文本

时间:2018-05-09 09:38:17

标签: javascript button

我已经将按钮的文字更改为" RETURN"每当我第一次点击它时,p标签内的文字就会改变为" ABC"到" Lorem ipsum"。有什么方法可以将文本改回" ABC"来自" Lorem ipsum"使用" RETURN"只用JavaScript的按钮?这是我的代码



var text = document.getElementById("info");
var btn = document.getElementById("btn");
btn.addEventListener("click", function() {
  text.innerHTML = "Lorem ipsum";
  btn.innerHTML = "RETURN";
});

body {
  margin: 0;
  text-align: center;
  font-size: 20px;
}

<p id="info">ABC</p>
<button id="btn">CLICK FOR MORE</button>
&#13;
&#13;
&#13;

5 个答案:

答案 0 :(得分:2)

您应该创建toggle()来更改文字;

&#13;
&#13;
var text = document.getElementById("info");
       var btn = document.getElementById("btn");
        btn.addEventListener("click", function() {
          text.innerHTML = "Lorem ipsum";
          btn.innerHTML = "RETURN";
          Toggle();
        });
        
        function Toggle() {
           if(btn.innerHTML === "Lorem ipsum") { 
     text.innerHTML = "Lorem ipsum";
     btn.innerHTML = "RETURN";
  } else {
      text.innerHTML = "RETURN";
     btn.innerHTML = "Lorem ipsum";
  }
        } 
&#13;
<p id="info">ABC</p>
<button id="btn">CLICK FOR MORE</button>
    
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您可以尝试以下

&#13;
&#13;
var text = document.getElementById("info");
var btn = document.getElementById("btn");
btn.addEventListener("click", function() {
      if(btn.innerHTML === "CLICK FOR MORE") { 
         text.innerHTML = "Lorem ipsum";
         btn.innerHTML = "RETURN";
      } else {
          text.innerHTML = "ABC";
         btn.innerHTML = "CLICK FOR MORE";
      }
    });
&#13;
body {
  margin: 0;
  text-align: center;
  font-size: 20px;
}
&#13;
<p id="info">ABC</p>
<button id="btn">CLICK FOR MORE</button>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

呀。您可以在外部设置变量来填充值。

var text = document.getElementById("info");
var btn = document.getElementById("btn");
var flipper = true;
btn.addEventListener("click", function() {
    text.innerHTML = flipper ? "Lorem ipsum" : "Prev text";
    flipper = !flipper;
    btn.innerHTML = "RETURN";
});

答案 3 :(得分:0)

您可以使用变量存储原始文本:

&#13;
&#13;
var text = document.getElementById("info");
var btn = document.getElementById("btn");
let formerText = "Lorem ipsum";
let formerBtn = "RETURN";
btn.addEventListener("click", function() {
  const tmpText = text.innerHTML;
  const tmpBtn = btn.innerHTML;
  text.innerHTML = formerText;
  btn.innerHTML = formerBtn;
  formerText = tmpText;
  formerBtn = tmpBtn;
});
&#13;
body {
  margin: 0;
  text-align: center;
  font-size: 20px;
}
&#13;
<p id="info">ABC</p>
<button id="btn">CLICK FOR MORE</button>
&#13;
&#13;
&#13;

答案 4 :(得分:0)

当你想将测试从ABC“改为”Lorem ipsum“和”Lorem ipsum“分别改为ABC时,我的意思是它与奇数或偶数点击有关或你想要点击按钮,文字是”ABC“然后将其更改为“Lorem ipsum”,反之亦然