gpt4 book ai didi

javascript - 如何让2个元素的InnerHTML在程序每次运行时切换

转载 作者:行者123 更新时间:2023-11-28 04:48:46 26 4
gpt4 key购买 nike

我的任务是做到这一点,以便当我按下运行时,两段文本会切换,因此“标题”文本出现在“新闻”中,反之亦然。

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;

我只是了解如何让它们切换,任何帮助和解释都会很棒,干杯。

最佳答案

可能的方法:

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>

关于javascript - 如何让2个元素的InnerHTML在程序每次运行时切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43121659/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com