使用javascript动态构建一个HTML标题标签 [英] build an html title tag dynamically with javascript

查看:191
本文介绍了使用javascript动态构建一个HTML标题标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在网站上开发了许多页面,其中每个页面都有自己的标题标签。在许多情况下,标题具有不变的文本,例如:

I have many pages on a site im developing, in which each page has its own title tag. In many cases the titles have constant text, for example:

首页|第1节| Page 1

首页|第1节| Page 2

首页|第1节|第3页等等

Home | Section 1 | Page 1
Home | Section 1 | Page 2
Home | Section 1 | Page 3, etc...

插入这些标题后,会更加难以改变,更不要说记住添加它们的麻烦。我正在寻找一种使用javascript动态生成每个页面的标题的方法,基于网站文件夹结构中页面的位置。

Inserting these titles makes for harder changes later on, not to mention the hassle of remembering to add them. I'm looking to find a method of dynamically generating the title of each page with javascript, based off the location of the page within the folder structure of the site.

Im目前正在使用一个类似于面包屑的脚本,但不知道如何引用相同的脚本,或者为页面标题构建类似的脚本。导航痕迹在这里: http://trcreative.us/dev/jmsracing/js/breadcrumbs .js

Im currently using a script that does something like this for breadcrumbs, but am not sure how to either reference the same script, or build a similar one for page titles. The breadcrumb script is here: http://trcreative.us/dev/jmsracing/js/breadcrumbs.js

,绝大多数情况下,我正在做所需的标题,减去每个面包屑项目的链接。 (我不想让它明显地标题)。

and for the most part doing exactly what I need for titles, minus links per each breadcrumb item. (I don't want it to do that for title's obviously).

请参阅这里应用的面包屑: http://trcreative.us/dev/jmsracing/races/pigman-long-and-olympic/

See breadcrumbs applied here: http://trcreative.us/dev/jmsracing/races/pigman-long-and-olympic/

任何帮助将不胜感激。谢谢

Any help would be appreciated. Thank you

推荐答案

假设您的网址如下 home / section / page.html 你可以使用这个功能在任何页面的顶部,它会根据url设置标题,如果这是你的意思。

Assuming that your url's are as following home/section/page.html you could use this function at the top of any page and it will set the title based on the url if that's what you mean.

function setTitle(extra) {
  document.title = location.pathname.split('/').map(function(v) {
    return v.replace(/\.(html|php)/, '')
      .replace(/^\w/, function(a) { return a.toUpperCase(); });
  }).join(' | ') + (extra && ' | '+ extra);
}

使用此功能将生成如下所示的标题:首页| Section |页。如果你想为特定页面添加特定的东西,然后传递一个字符串作为 extra 参数,它将被添加到标题ie。

Using this function will generate a title like this: Home | Section | Page. If you want to add specific stuff for a particular page then pass a string as the extra parameter and it will be added to the title ie.

// url: http://mypage.com/home/about/frogs    
setTitle('Frogs are awesome');
console.log(document.title); //=> Home | About | Frogs | Frogs are awesome

这篇关于使用javascript动态构建一个HTML标题标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆