纯js点击按钮切换首页部分页面

像我这种大数据的,不会前端的,懒得学框架,现在有gpt了,前端对于我来说,用原生的更加友好,毕竟算法gpt都能优化。

首页我有个页面,然后我现在想点击gm替换上面的统计,点击用户替换回来

纯js点击按钮切换首页部分页面_第1张图片

现在我要点击GM,就会把这一栏替换掉,其他的页面是不改变的

纯js点击按钮切换首页部分页面_第2张图片

 

上面那一栏的结构如下

纯js点击按钮切换首页部分页面_第3张图片

 

 从index.html有一个默认的页面,然后gm和zhuBo的单独的页面,他们只有一个div,div里面就写了一个id

然后index.html里面写js

//本页面中要被替换的
const headRight = document.getElementById('headRight');
//切换的按钮
const loadPage1Button = document.getElementById('loadPage1');
const loadPage2Button = document.getElementById('loadPage2');

//pageURL你要提取的页面,contentContainer本页面的位置,待提取页面用来替换的divId
function loadAndReplaceContent(pageURL,contentContainer,divId) {
    fetch(pageURL)
        .then(response => response.text())
        .then(pageContent => {
            const parser = new DOMParser();
            const doc = parser.parseFromString(pageContent, 'text/html');
            const targetDiv = doc.querySelector(divId); // 替换为你要提取的 div 的 ID 或选择器

            if (targetDiv) {
                contentContainer.innerHTML = ''; // 清空内容容器
                contentContainer.appendChild(targetDiv.cloneNode(true)); // 将提取的 div 插入到内容容器
            } else {
                console.log('Div not found in the loaded content.');
            }
        })
        .catch(error => {
            console.error('Error loading content:', error);
        });
}

loadPage1Button.addEventListener('click', () => {
    loadAndReplaceContent('module/zhuBo.html',headRight,'#headSta');
});

loadPage2Button.addEventListener('click', () => {
    loadAndReplaceContent('module/gm.html',headRight,'#headSta');
});

你可能感兴趣的:(javascript,开发语言,ecmascript)