简体   繁体   English

如何在CSS链接标签中插入JavaScript函数

[英]How to insert javascript function in css link tag

How can we call a javascript function inside some css link tag ? 我们如何在某些CSS链接标记内调用javascript函数?

For example: 例如:

<link rel="stylesheet" href="https://<%=getServerIP()%>/path/to/cssFiles/file1.css" type="text/css">

As we can see that, this scriplet works just fine. 正如我们所看到的,此代码片段工作正常。 It calls scriptlet function. 它调用scriptlet函数。 Grabs the IP. 抢IP。 Access the css file. 访问css文件。

I need to do the same thing with javascript function. 我需要用javascript函数做同样的事情。

<link rel="stylesheet" href="https://'getServerIP()'/path/to/cssFiles/file1.css" type="text/css">

Why not the second way is not working ? 为什么第二种方式不起作用? Any work around ? 有什么解决方法吗?

Thanks in advance. 提前致谢。 :) :)

There is no similar syntax in javascript for dropping variables into the html like you can in PHP. 在JavaScript中,没有类似的语法可以像在PHP中一样将变量拖放到html中。 In order to dynamically load a CSS file in javascript, you would need to create a link element and append it to the head. 为了在javascript中动态加载CSS文件,您需要创建一个link元素并将其附加到头部。 Something like this: 像这样:

function loadCssFile(filename){
  var linkElement=document.createElement("link");
  linkElement.setAttribute("rel", "stylesheet");
  linkElement.setAttribute("type", "text/css");
  linkElement.setAttribute("href", filename);
  document.getElementsByTagName("head")[0].appendChild(linkElement);
}

var url = 'https://'+getServerIP()+'/path/to/cssFiles/file1.css';
loadCssFile(url);

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

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