仍然无法正常工作。用.js变量交换.innerHTML

时间:2018-10-02 10:17:12

标签: javascript html

用户访问页面时,必须显示此HTML文本。

<p id="exampleText">Hit The "Change Text" Button Below To Change <span id="thisText"><strong>This</strong></span> Text and see how the innerHTML property tag works </p>

点击此按钮后:

<button id="changeButton" type="button" value="default Text" onclick="textChanger()">Change Text</button>

显示此文本:

var txtExmp1 = "Hooooooooooooraayy!!, You Clicked and Changed The Text..." + "<br><br><br>" + "but now you have to fix me so i can change again";

现在,用户应该可以单击按钮并查看以前的文本,并返回到var txtExmp1中的“万岁”消息。

我尝试使用if语句,但是没有用。这是代码:

var defaultText = document.getElementById("exampleText");

      if (defaultTex.innerHTML === defaultText){
          defaultText.innerHTML = txtExmp1;
      }  
      else {
          defaultText.innerHTML = defaultText;
      }

如何考虑一个是html而另一个是javascript,如何使这些文本彼此切换。切换此文本最简单,最有效的方法是什么?

这里是什么样子(屏幕截图): i.Before Click ii.After click, but wont change again

2 个答案:

答案 0 :(得分:1)

这是相对简单的,当更改文本时,您需要将当前可见的文本保存到变量中,然后在txtExmp1中显示您存储的其他文本,然后在再次单击时使用其他可见的文本会存储它并显示您之前存储的文本,这样做效率很低。

从一开始就将两个字符串都存储在变量或数组中,然后在它们之间切换。

当然,这只是实现这一目标的一种方法。

let text = ["Hooooooooooooraayy!!, You Clicked and Changed The Text... <br><br><br>but now you have to fix me so i can change again", "Hit The Change Text Button Below To Change <span id='thisText '><strong>This</strong></span> Text and see how the innerHTML property tag works "];
let index = 0;

function textChanger() {
  // Get the p Element refrence so we can modify it
  var pElement = document.getElementById("exampleText");
  // text[index] will return one of the texts from the array
  // depening on the index if 0 its the first one
  // if 1 it's the second one
  // that's why we're altering index's value after every change
  
  if (index == 0) {
    pElement.innerHTML = text[index];
    index = 1;
  } else if (index == 1) {
    pElement.innerHTML = text[index];
    index = 0;
  }
}
<p id="exampleText">Hit The Change Text Button Below To Change <span id='thisText '><strong>This</strong></span> Text and see how the innerHTML property tag works </p>

<button id="changeButton" type="button" value="default Text" onclick="textChanger()">Change Text</button>

答案 1 :(得分:0)

您要搜索的单词已切换。尝试开关盒:

var theToggle = document.getElementById("changeButton");
var toggleMe = document.getElementById("exampleText"); 
toggleMe.toggleStatus = "on";

theToggle.onclick = function(){
  switch(toggleMe.toggleStatus){
    case "on":
      toggleMe.toggleStatus="off";
      toggleMe.textContent = "Hooooooooooooraayy";
      break;
    case "off":
      toggleMe.toggleStatus="on";
      toggleMe.textContent = " Hit The Change Text Button Below To change...";
      break;
  }

祝你好运!