【问题标题】:How to make InnerHTML of 2 elements switch every time the program is run每次程序运行时如何使2个元素的InnerHTML切换
【发布时间】:2017-03-30 15:05:59
【问题描述】:

我的任务是这样当我按下运行时,两条文本切换,所以“标题”文本出现在“新闻”中,反之亦然。

var headline = document.getElementById("headline");
var headline2 = "Student Wins Lottery";
headline.innerHTML = headline2;

var news = document.getElementById("news");
var news2 = "A student has won a million pounds";
news.innerHTML = news2;

我只是对你如何让他们切换,任何帮助和解释都很好,干杯。

【问题讨论】:

  • js和html代码要分开

标签: javascript variables innerhtml


【解决方案1】:

可能的方法:

var headline = document.getElementById("headline"),
    headline2 = document.getElementById("news"),
    str1 = "Student Wins Lottery",
    str2 = "A student has won a million pounds",
    bool = true;

function change() {
  if (!bool) {
    headline.innerHTML = str1;
    news.innerHTML = str2;
    bool = true;
  } else {
    headline.innerHTML = str2;
    news.innerHTML = str1;
    bool = false;
  }
}
<h1 id="headline">Student Wins Lottery</h1>
<div id="news">A student has won a million pounds</div>
<button onclick="change()">change heading</button>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-30
    • 1970-01-01
    • 1970-01-01
    • 2017-05-09
    • 2014-11-28
    • 2018-01-11
    • 2013-05-19
    • 1970-01-01
    相关资源
    最近更新 更多