我现在正在尝试用函数的js onclick来实现页面布局的改变,问题是,如何让js显示当前的正文html?
逻辑如下:
首先我有我的页面html和主体dom,然后我有我定义的脚本,如果你点击按钮,你会有不同的内容显示,使用pageLayout.innerHTML = "<p>this is the new content</p>"
。
但是我如何让js显示最后的内容,或者返回到正文中脚本顶部定义的内容,而不是复制粘贴两次,最后使用相同的函数?
发布于 2021-08-15 19:54:40
在进行任何更改之前,您可以将以前的内容存储在全局变量中。
所以,如果你想用同样的按钮恢复内容,你可以这样做:
let previousContent = "";
function handleClick() {
// Find the element that you want to change its content
const pageLayout = document.getElementById("layout");
// Check if there is any stored content
if(previousContent) {
pageLayout.innerHTML = previousContent;
//Clear the stored content
previousContent = "";
} else {
// Store the previous content
previousContent = pageLayout.innerHTML;
//Create the new content
const newContent = " your new content";
//Update the content
pageLayout.innerHTML = newContent;
}
}
const button = document.getElementById("my-button-id");
button.addEventListener("click", handleClick);
https://stackoverflow.com/questions/68793985
复制相似问题