我试图了解模板的基础知识并遇到以下问题。当我尝试将ID
或/和type
属性附加到我的HTML代码中的<script>
标记时,它就不起作用了:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="somescript.js"></script>
</head>
<body>
<script type="text/html" id="template1">
<form name="formXY">
<p>
<label>Field1
<input type="text" name="form_field1" value= "{{field1}}">
</label>
<button type="button">Submit</button>
</p>
</form>
</script>
</body>
</html>
我在chrome / firefox / IE9 / Opera中运行它,但没有一个解析<script>
标签之间的代码。浏览器认为它只是一个文本字段。当我删除ID
和type
属性时,它会再次正确解析。
我可能遗漏了一些非常基本的东西......
答案 0 :(得分:2)
您需要在脚本代码中添加非javascript type
,因为您不希望浏览器解析它(作为javascript),并使用自定义type
浏览器会忽略它(直到你用javascript抓住它)
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="somescript.js"></script>
</head>
<body>
<script type="text/x-handlebars-template" id="template1">
<form name="formXY">
<p>
<label>Field1
<input type="text" name="form_field1" value= "{{field1}}">
</label>
<button type="button">Submit</button>
</p>
</form>
</script>
</body>
</html>
然后在您的javascript somescript.js
中,您需要使用类似的内容获取该脚本代码的内容
var uncompiledTemplate = document.getElementById('template1').innerHtml;
// then pass this template to your templating engine...
// if your using handlebars:
var template = Handlebars.compile(uncompiledTemplate);
然后你就可以使用你的模板了!
答案 1 :(得分:0)
<script>
标记的内容永远不会被解析为DOM元素,内容只是作为文本显示在DOM中(尽管<script>
默认为display:none;
,因此它不会出现在这页纸)。如果提供type
必须是浏览器在尝试执行它之前识别的那个。请注意,旧浏览器使用的是language
属性。