使用 javascript 设置 html 页面的标题

set the title of an html page using javascript

页面标题由外部设置javascript。我找不到执行此操作的确切功能。所以我写了一个函数并将它放在 html 文件中。但它仍然显示前一个 javascript 函数的标题。

<script type="text/javascript">

$(document).ready(function() {
    document.title = 'Pry';
});

 </script>

您也可以尝试定期更改标题。因为您不知道脚本何时真正更改标题。

setInterval(function() {
   document.title = 'Pry';
}, 1000);

如果脚本更改一次标题,您也可以在标题更改后停止此计时器

var title = 'Pry';
var count = 0;
var timer = setInterval(function() {

    if (document.title !== title)
       count += 1;

    document.title = title;

    // count will be incremented twice
    // once when this function runs for first time
    // when title is actually changed
    if (count >= 2)
        clearInterval(timer);

}, 1000);

最好编辑实际更改标题的脚本,而不是编写另一个例程来更改标题。

如果可能的话,您最好倾听用例中的变化。

$(document).ready(function () {
  $("title", "head").change(function () {
      console.log("Title has changed");
      changeTitle();
  });

  //Trigger Change
  function changeTitle() {
      $("title", "head").text("New Title");
  }

  $("title","head").text("test Title").trigger('change'); // triggered elsewhere
});