zoukankan      html  css  js  c++  java
  • 如何动态修改网页的标题(title)?

      有时候我们需要复用一个页面,但是又希望他们拥有各自的标题,这时候就需要动态的去更改页面的title了,不然所有页面都是一个标题。

      这时候就会想到使用js或jQuery去实现了。

      1、js方式。

      首先,我想到了使用document.getElementsByTagName()去获取页面的title标签,这是可以获取的。例如:

    <title>标题</title>
    <script>
        var Title = document.getElementsByTagName('title')[0]
        console.log(Title)  // <title>标题</title>
    </script>
    

      然而,当我想用Title.title去获取或设置值时是不生效的。

      获取title值: console.log(Title.title) 会发现是无法获取到值的

      同理,设置网页title值: Title.title = 'hello world!' 会发现网页的标题也是没有被更改的

      所以通过这种方法是无法获取和更改网页的title的。

      

      其实,我们可以通过document.title来直接获取title值或者设置title值

    <title>标题</title>
    <script>
        document.title = 'hello world!'
    </script>
    

      结果:

        

      可以发现这个办法是行得通的。

      2、jQuery方式

    <title>标题</title>
    <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script>
    <script>
        $(function(){
          $('title').html('hello!') // 此处也可以使用text()方法
        })
    </script>
    
  • 相关阅读:
    【luogu P4139】 上帝与集合的正确用法
    pb_ds学习
    【luogu P3868】 [TJOI2009]猜数字
    BZOJ3040: 最短路(road)
    【luogu P1064】 金明的预算方案
    【luogu P2893】 [USACO08FEB]修路Making the Grade
    【luogu P2801】 教主的魔法
    UVA10816 Travel in Desert
    P2916 [USACO08NOV]安慰奶牛Cheering up the Cow
    【BZOJ 2054】 疯狂的馒头
  • 原文地址:https://www.cnblogs.com/sunjuncoder/p/9895121.html
Copyright © 2011-2022 走看看