在哪里存储仅与 JavaScript 一起使用的少量 HTML?

发布于 2024-10-15 03:36:56 字数 281 浏览 10 评论 0原文

我正在使用一个小型 HTML 模板,其中包含一些 DIV 和一些标头(大约 15 行代码)。该模板填充的文本取自用户从页面其他部分选择的选项。仅当用户启用了 JavaScript 时,标记才有用。如果用户选择多个选项,它也会被克隆。

存储此模板的最佳方式是什么(根据最佳实践)?

  1. 看起来将它存储在 JS 中是有意义的,因为它仅与 JS 一起使用,但后来我知道最好将行为和标记分开。
  2. 在主页中插入标记,然后将其设置为在样式表中不显示,然后在 JavaScript 中显示块。

I have a small template of HTML that I am using that contains a few DIVs, and a few headers (roughly 15 lines of code). This template is populated with text taken from options that a user selects from another part of the page. The markup is only of any use if the user has JavaScript enabled. It is also cloned if the user selects multiple choices.

What would be the best way to store this template (according to best-practices)?

  1. It seems like storing it in the JS would make sense, since it's only used with JS, but then I know it's best to separate behavior and markup.
  2. Insert the markup in the main page and just set it to display none in the stylesheet, then display block in the JavaScript.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

涫野音 2024-10-22 03:36:56

对于可维护性,我认为#2 是最好的。如果您将标记保留在外部 JS 文件中,甚至保留在脚本部分中,那么当标记更新时,它可能会被忽略或忘记。如果您使用 CMS 工具,那么将其保留在标记中会更有意义。我通常回避在 javascript 中保留 html 标记,因为在转义字符和生成兼容标记时很容易犯错误。

for maintainability I would say #2 is best. If you keep markup in a external JS file or even in the script section it may be ignored or forgotten when the markup is updated. If you are using a CMS tool then it would make more sense to keep it in the markup. I usually shy away from keeping html markup in javascript as it would be easy to make mistakes with escaping characters, and generating compliant markup.

树深时见影 2024-10-22 03:36:56

在这种具体情况下,由于克隆,在我看来,没有令人满意的解决方案。

我会使用第二个,因为在第一个中,您在 JS 中“存储 HTML”...但我认为这个“存储”是通过包含 HTML 的字符串完成的。所以字符串将被评估(使用 jQuery 或innerHTML 属性)。这并不是真正的干净和高效。

此外,使用第二种解决方案,您可以使用 WYSIWIG 编辑器等来编辑 HTML。

In this specific case, because of the clone, from my opinion, there is no satisfying solution.

I would use the second, because in the first you "store HTML" in JS... but I suppose this "storage" is done with a string containing HTML. So the string will be evaluated (with jQuery or innerHTML attribute). This is not really clean and efficient.

Moreover, with the second solution, you can edit your HTML with a WYSIWIG editor for instance.

静待花开 2024-10-22 03:36:56

第一个选择更好,因为它更干净。

1st choice is better because it will be cleaner.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文