首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何用js onclick显示当前html页面?

如何用js onclick显示当前html页面?
EN

Stack Overflow用户
提问于 2021-08-15 17:43:05
回答 1查看 38关注 0票数 0

我现在正在尝试用函数的js onclick来实现页面布局的改变,问题是,如何让js显示当前的正文html?

逻辑如下:

首先我有我的页面html和主体dom,然后我有我定义的脚本,如果你点击按钮,你会有不同的内容显示,使用pageLayout.innerHTML = "<p>this is the new content</p>"

但是我如何让js显示最后的内容,或者返回到正文中脚本顶部定义的内容,而不是复制粘贴两次,最后使用相同的函数?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-08-15 19:54:40

在进行任何更改之前,您可以将以前的内容存储在全局变量中。

所以,如果你想用同样的按钮恢复内容,你可以这样做:

代码语言:javascript
运行
复制
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);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68793985

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档