使用新标题重新加载 html 页面

Reload html page with new title

本文关键字:页面 加载 html 新加载 标题 新标题      更新时间:2023-09-26

我在单个html文档中具有相同的页面(或锚标记)链接。当用户单击这些链接时,他们会在新选项卡中打开相同的 html 文档。

新选项卡如何具有新的文档标题?

下面的代码的问题在于它重命名了当前选项卡的标题(而不是刚刚打开的新选项卡)。我的页面有一个默认标题,我希望在您首次加载页面时拥有该标题。当然,所有后续加载的新页面都会为其标题设置此内容。

<title>Default title</title>
<a href=#relativeLink target='_blank' onclick="return runMyFunction();">click me</a>
<script>
    function runMyFunction() {
        document.title="new title!"
        return true;
    }
</script>

有两种方法可以实现此目的1、将标题作为网址参数传递2,将所有标题保存在一个数组中,并传递标题数组的选定标题索引

<html>
  <head>
    <title>Default title</title>
  </head>
<body>
    <a href="?newTitle=My new title" target="_blank" >newTitle equal to My title 1</a>
    <a href="?newTitle=My new title 2" target="_blank" >newTitle equal to My title 2</a>
    <a href="?newTitle=My new title3" target="_blank" >newTitle equal to My title 3</a>
    <br />
    <a href="?tIdx=0" target="_blank" >tIdx equal to 0</a>
    <a href="?tIdx=1" target="_blank" >tIdx equal to 1</a>
    <a href="?tIdx=3" target="_blank" >tIdx equal to 2</a>
    <script>
        var titles = ["title 1", "title 2", "title 3" , "title 4"];

        function getUrlParameterValueByName(name) {
            name = name.replace(/['[]/, "'''[").replace(/[']]/, "''']");
            var regexS = "[''?&]" + name + "=([^&#]*)";
            var regex = new RegExp(regexS);
            var results = regex.exec(window.location.search);
            if (results == null)
                return "";
            else
                return decodeURIComponent(results[1].replace(/'+/g, " "));
        }
        var newTitleValue = getUrlParameterValueByName('newTitle');
        var titleIndex = getUrlParameterValueByName('tIdx');
        if (newTitleValue)
            document.title = newTitleValue;
        if (titleIndex)
            document.title = titles[titleIndex];

    </script>
</body>
<html>

如果打开的新选项卡是您创建的页面,请在加载页面时更改标题。您可以检查推荐人。如果新选项卡是您无法更改其标题的外部页面,则只需创建自己的页面即可在 iframe 内显示外部页面。

<title>My Title</title>
<iframe src="/path/to/external" />