使用JavaScript将样式表附加到html文档的头部

Appending a stylesheet to the head of an html document using JavaScript

本文关键字:html 文档 头部 JavaScript 样式 使用      更新时间:2023-09-26

我正试图在下载jQuery之前将其添加到html文档中。我需要在文档的开头附加以下内容:

<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/themes/base/jquery-ui.css"/>

我曾尝试使用以下方法来完成这项工作,但我最终得到的只是文档中的一对空标签:

var head = content.document.getElementsByTagName('head')[0];
var jqstyle = document.createElement("link");
    jqstyle.rel = "stylesheet";
    jqstyle.type = "text/css";
    jqstyle.href = "http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/themes/base/jquery-ui.css";
head.appendChild(jqstyle);

有人能告诉我我需要做些什么不同的事情吗?

谢谢

正如Fabricio所指出的,css文件的url中遗漏了两个字母(u和i)。

这在这里很好(注意注释中的url和实际使用的url之间的区别):

// want to create this and add to the doc head
// <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/themes/base/jquery-ui.css"/>
var link = document.createElement('link');
link.rel = "stylesheet";
link.type = "text/css";
link.href = "http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/themes/base/jquery-ui.css";
document.head.appendChild(link);

这也可以。

$('head').append('<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jquery/ui/1.7.1/themes/base/jquery-ui.css"/>');