2017-02-03 74 views
1

如果页面名为mypage.html,我想让下面的javascript更新特定的css链接bootstrap.min.js。
我该怎么做?如何让JavaScript修改基于页面名称的CSS链接?

<html> 
    <head> 

    <link rel="stylesheet" type="text/css" href="/css/bootstrap377.min.css"/> 
    <link rel="stylesheet" type="text/css" href="/css/some_other_stylesheet.css"/> 

    <script type="text/javascript"> 
    var filename = location.href.split("/").slice(-1); 

    if (filename == "mypage.html") { 
     HOW DO I DO THIS: update the above stylesheet link to be bootstrap400.min.css (or should this script be before the css link?) 
    } 
    </script> 


    </head> 
    <body> 
    this is a test 
    </body> 
</html> 
+0

不能从HTML – Nelu

+0

我的例子已经访问访问文件名的文件名,我需要的脚本来修改CSS链接 – user3302169

回答

1

使用document.querySelector去的link元素的引用,然后更改href财产通常的方式。

var filename = location.href.split("/").slice(-1); 

if (filename == "mypage.html") { 
    var link = document.querySelector("link[href='/css/bootstrap377.min.css']"); 
    link.href = "/css/bootstrap400.min.css"; 
} 
+0

好极了!但是我应该提到我的真实世界应用程序有多个css链接,因此唯一要更新的链接是包含“bootstrap.min.css”的链接。我会怎么做? – user3302169

+0

@ user3302169我更新了我的解决方案。您可能需要使用有多个链接的信息编辑您的问题。 –