如果刷新标签链接则返回 index.html

问题描述 投票:0回答:3

我正在制作一个网站,我使用的整个 jQuery 脚本都表现得很奇怪,一旦有人点击刷新 - 所以我认为当有人刷新时,他们的 URL 从让我们说

www.website.com/index.html#test
到只是
www.website.com/index.html
...这是可能,如果可能,如何?

javascript html redirect hashtag
3个回答
0
投票

你可以做的是检查 url 是否包含哈希值:

var url=window.location;
if(url.indexOf('#')!=-1){
   window.location = 'index.html';
}

indexOf
的作用是检查一个字符串是否包含某个子字符串,如果包含则返回该子字符串所在位置的索引,如果找不到则返回 -1 所以 我们在那里所做的是检查它是否不等于 -1,这意味着子字符串存在然后我们想转到 index.html


0
投票
window.onbeforeunload = function(e) 
{
    window.location = "index.html#introduction";
};

这使您可以将刷新重定向到另一个部分,但它似乎无法重定向到 index.html


0
投票

我的申请也有类似的问题。我是一个普通的 HTML、普通的 JS 和普通的 CSS 应用程序。

window.addEventListener("hashchange", onRouteChanged);

function onRouteChanged() {
    const hash = window.location.hash;

    const routerView = document.getElementById("router-view");

    if (!(routerView instanceof HTMLElement)) {
        throw new ReferenceError("No router view element available for rendering");
    }

    switch (hash) {
        case '#about':
            routerView.innerHTML = `<section id="about">
                                        <div class="title-box">
                                            <h3>About</h3>
                                            <hr/>
                                        </div>
                                        <h4></h4>
                                        <footer>
                                            <span>© 2023 Creator of The Quotes Room</span>
                                        </footer>
                                    </section>`;
            about();
            break;
        case "#home":
            window.location = "index.html"
            break;
        default:
            routerView.innerHTML = "<h1>404 - Page Not Found</h1>";
            break;
    }
}
<header>
        <section>
            <img src="img/Quotes room.png" alt="logo" target="logo">
            <h1>The Quotes Room</h1>
            <nav>
                <ul>
                    <li><a href="#home">Home</a></li>
                    <li><a href="#about">About</a></li>
                    <li><a href="#contact">Contact</a></li>
                    <li><input type="text" placeholder="Search.."></li>
                </ul>
            </nav>
        </section>
    </header>

如您所见,我使用哈希从一个页面路由到另一个页面。 A 对我来说,它适用于:

window.location = "index.html"
© www.soinside.com 2019 - 2024. All rights reserved.