【问题标题】:access to contents of script tag with src attribute (template including) [duplicate]使用 src 属性访问脚本标签的内容(包括模板)[重复]
【发布时间】:2012-11-05 17:40:21
【问题描述】:

可能重复:
How to outsource a template js to a different file when using Handlebars.js

我正在使用手把。他们建议在文档正文中包含这样的模板:

<script id="entry-template" type="text/x-handlebars-template">
     template content
</script>

我想通过 src 属性使用模板内容并将我的模板(大量)存储在单独的文件中。

<script src="/path/to/my.template" id="entry-template" type="text/x-handlebars-template"></script>

问题是如何访问co内容呢?

$('script#entry-template').html() //returns ""
$('script#entry-template').text() //returns ""

【问题讨论】:

  • 你能做一个 ajax get 来检索文件的内容吗?
  • 谢谢。搜索没找到
  • 这个想法是使用浏览器标准机制。当它遇到带有 src 属性的脚本标签时,它会加载它。或不?我已经通过 $('head').append('') 对其进行了测试,并看到了 XMLHttpRequest。 jquery 执行了吗?
  • "text/javascript" 以外的任何其他类型都将转义
  • 旁注:id不是script标签的常规属性,看到它用在Handlebars中我很惊讶。

标签: javascript jquery handlebars.js


【解决方案1】:

您需要获取 src 属性的值,然后使用 XMLHttpRequest 请求 URI……此时最好不要使用 &lt;script type="not-js"&gt;

浏览器不会自动下载未知的脚本类型,也不会让 JS 以编程方式访问脚本。您可以访问 内联 脚本,因为它们是 DOM 的一部分,而外部脚本不是。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-05
    • 2011-10-18
    • 2012-11-12
    • 2016-09-04
    • 1970-01-01
    • 1970-01-01
    • 2015-12-08
    • 1970-01-01
    相关资源
    最近更新 更多