使用JavaScript添加内容后重新应用样式 [英] Reapply style after adding content with JavaScript

查看:58
本文介绍了使用JavaScript添加内容后重新应用样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将尝试扩大我的问题:

I will try to expand my problem:

我有一个链接:

<a href="#" onClick="Display(); return false;">Display</a>

我有一些风格:

<style type="text/css">
p {
 background-color: #AFA99B;
}
</style>

以及以下js代码:

function printf(MyHtml){
document.write(MyHtml); 
}

function Display(){
printf("<p>some html code<p>");
//...
}

因此,当用户单击链接时,我必须在正文中添加一些html内容&新添加的元素必须使用定义的样式.就是这样.

So when the user click the link, I must add some html content to the body & the new added elements must use the styles defined. That's all.

推荐答案

这就是我的评论中提到的问题.文档完全加载后,您正在调用 document.write(MyHtml) .

That's the problem was talking about in my comment. You are calling document.write(MyHtml) after the document was fully loaded.

它将完全替换文档(请参见文档).检查它,您将看到一个空的 head (另请参见示例).

It will completely replace the document (see the documentation). Inspect it, you will see that there is an empty head (also see this and this example).

使用其他方法来操作DOM .

这篇关于使用JavaScript添加内容后重新应用样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆