简体   繁体   English

如何刷新document.write上的页面

[英]How to refresh the page on document.write

I am using document.write in a function to give different CSS to user's based on their choosing. 我在函数中使用document.write根据用户的选择为用户提供不同的CSS。

function blue() {
    document.write('<link rel="stylesheet" type="text/css"  href="http://ilam.irib.ir/documents/697970/237563314/blue.css" />');
}

I am calling the function from an anchor tag. 我从锚标记调用函数。

function color2(){
    document.getElementById("navigation").innerHTML +='<a class="myButton" onclick="blue()" background-color:"#05c8f2";></a>'; 
}

As you can guess, when the link is clicked, the page clears out and I get a blank page. 如您所料,单击链接后,页面将被清除,我得到一个空白页面。

Is there any way to fix this problem? 有什么办法可以解决这个问题? I don't want to stop page refreshing, I'm just trying to fix the problem in any way possible! 我不想停止页面刷新,我只是想以任何可能的方式解决问题!

Note: don't ask why I'm adding code using JavaScript, and not directly into HTML code. 注意:不要问为什么我要使用JavaScript而不是直接添加到HTML代码中来添加代码。 This site is a large scale system and we just have access to JavaScript and CSS. 该站点是一个大型系统,我们只能访问JavaScript和CSS。 So this is all we can do to edit our pages. 这就是我们可以编辑页面的全部操作。

document.write rewrites the body , as a result the only thing in your document remains is the css file you added and hence it is blank. document.write重写body,结果文档中唯一剩下的就是添加的css文件,因此该文件为空。

View this 查看这个

Code from above link :- 上面链接的代码:-

var cssId = 'myCss';  // you could encode the css path itself to generate id..
if (!document.getElementById(cssId))
{
  var head  = document.getElementsByTagName('head')[0];
  var link  = document.createElement('link');
  link.id   = cssId;
  link.rel  = 'stylesheet';
  link.type = 'text/css';
  link.href = 'http://website.com/css/stylesheet.css';
  link.media = 'all';
  head.appendChild(link);
}

Instead of rewriting while dom , we append the link element inside head tag 除了在dom时重写外,我们在head标签内附加link元素

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

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