繁体   English   中英

根据 URL 更新页面标题

[英]Updating Page Title Based on URL

假设example.com<title>example

如何自动将example.com/#city1的页面标题更新为example.com/#city1 example city1 ,将example.com/#city2的页面标题自动更新为example.com/#city1 example city2等等。

我只有一个index.html文件,我不想将php文件添加到我的 html 文件中,所以请帮我写一个简单干净的代码。

如果您需要动态解决方案,则每次锚点/哈希更改时都会更新页面标题:

$(function(){
  // event
  $(window).on('hashchange', function() {
    let hash = location.hash.replace( /^#/, '' );
    document.title = 'example ' + hash;
  });

  // just to set on page load (you might need to tweak in case there is no hash)
  $(window).trigger('hashchange');
});

您必须至少使用 javascript。

尝试这个:

 var str = 'example.com/#city1'; var str1 = str.substring(0,str.indexOf('.'))+' '+str.substring((0,str.indexOf('#')+1)); document.getElementsByTagName('p')[0].innerHTML = str1; //in your case replace p with title tag
 <p>Change Me</p>

暂无
暂无

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

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