简体   繁体   English

使用javascript设置html页面的标题

[英]set the title of an html page using javascript

A title of an page is set by external javascript. 页面标题由外部javascript设置。 I cannot find the exact function which does it. 我找不到执行此操作的确切功能。 So i wrote a function and placed it in the html file. 因此,我编写了一个函数并将其放置在html文件中。 But still it is showing title of the previous javascript function. 但它仍显示以前的javascript函数的标题。

<script type="text/javascript">

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

 </script>

You can also attempt to change title periodically. 您也可以尝试定期更改标题。 As you don't knows when scripts actually changes the title. 您不知道脚本何时实际更改标题。

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

If script changes title once, you can also stop this timer once title is changed 如果脚本一次更改了标题,则更改标题后也可以停止此计时器

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);

It will be better you edit script that is actually changing the title instead of writing another routine to change the title. 最好编辑实际上是在更改标题的脚本,而不是编写另一个例程来更改标题。

You'll be best listening for a change, if possible, in your use case. 如果可能,在用例中,您最好倾听更改。

$(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
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM