使用 Javascript 注入 HTML 代码
我有一个简单的 html 片段,在运行时将其添加到文档中。我正在使用 jQuery 的选择器,但这应该与我面临的问题无关。
使用时: $("#elementID").html()
显示代码,但未应用 CSS。该行为是有意义的,因为 CSS 已经被加载并应用。
我的问题是: - 是否可以“刷新” DOM 元素,以便在其 html 内容更改后重新应用 CSS? - 或者有没有办法在将 JavaScript 添加到 DOM 元素之前将 CSS 应用于 JavaScript 中的代码?
我知道各种 JS\html 模板库,但在这个阶段,我试图尽量减少对额外库的依赖,特别是因为我生成\注入的片段非常简单,我不介意它们留在 JS 代码
中
I have a simple html snippet that I add to the document during runtime. I am using jQuery's selectors but that should irrelevant to the issue I am facing.
When using:
$("#elementID").html()
The code is displayed but with no CSS applied. The behaviour make sense since the CSS has already been loaded and applied.
My questions are:
- Is there away to "refresh" a DOM element in order to re-apply CSS on it after its html content has been changed?
- or is there a way to apply CSS on the code I have in the JavaScript before adding it to the DOM element?
I am aware of various JS\html templates library but at this stage I am trying to minimize the dependency on extra libraries, specially since that the snippets I am generating\injecting are very simple and I dont mind them staying in the JS code
Jamil
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您错了。 CSS 始终被应用(在运行时) - 看看这个 jsFiddle 示例。你把别的事情搞砸了。
You are wrong. CSS is applied all the time (during runtime) - look at this jsFiddle example. You messed up with something else.
你确定没有应用css吗?因为它应该是。如果您向 DOM 添加新元素,它应该采用您已加载的任何 css 文件的样式。你是如何应用CSS的?
Are you sure css is not applied? Because it should be. If you add a new element to the DOM, it should just take on the styling from any css files you have loaded. How are you applying the css?
如果需要,元素上的
.trigger('create')
将强制重新渲染元素.trigger('create')
on the element will force a re-rendering of the element if needed