javascript 在javascript中访问文本/模板内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6232988/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 20:00:43  来源:igfitidea点击:

Accessing text/template contents in javascript

javascriptjquerytemplates

提问by Spencer Alger

I'm trying to access the html contents of an script block with the type set to "text/template". I've heard of template engines using such tags, but my application is very simple and loading an entire engine is unnecessary. Can someone shed some light on how I select that element? I think jQuery's .html() function will get me the content but I can't seem to find the element.

我正在尝试访问类型设置为“文本/模板”的脚本块的 html 内容。我听说过使用此类标签的模板引擎,但我的应用程序非常简单,无需加载整个引擎。有人可以阐明我如何选择该元素吗?我认为 jQuery 的 .html() 函数将为我提供内容,但我似乎无法找到该元素。

The template looks like:

模板看起来像:

<script type="text/template" id="repeating-form-section-template">
  <div class="repeating-form-section">
    <label>Field Name:</field>
    <input type="text" value="default value" name="field_name" />
  </div>
</script>

Things I've tried:

我尝试过的事情:

getElementById('repeating-form-section-template');
$('script').filter(...);
$('#repeating-form-section-template');
$("script[type='text/template']");

Thanks!

谢谢!

采纳答案by Niklas

Both:

两个都:

 $('#repeating-form-section-template');
 $("script[type='text/template']");

Work fine. Make sure you check them after DOM load. Example: http://jsfiddle.net/niklasvh/VKqPX/

工作正常。确保在 DOM 加载后检查它们。示例:http: //jsfiddle.net/niklasvh/VKqPX/

回答by Oscar Godson

It should be this easy:

应该这么简单:

http://jsbin.com/evozi5/edit

http://jsbin.com/evozi5/edit

For a preview: http://jsbin.com/evozi5/

预览:http: //jsbin.com/evozi5/

The code tho is simply:

代码很简单:

var someVar = $('#repeating-form-section-template').html();

$('#where-i-want-content').append(someVar);

Note

笔记

jQuery must be loaded beforethis will work tho. So:

必须先加载 jQuery,然后才能正常工作。所以:

<script src="jquery.js"></script>
<script> /* your code */ </script>
<script type="text/template"></script>

回答by AsherMaximum

innerHTMLis generally considered a bad thing to use, but it's the perfect thing to use here:

innerHTML通常认为使用不好,但在这里使用它是完美的:

var template = document.getElementById("repeating-form-section-template").innerHTML;

document.getElementById('where-you-want-the-content').innerHTML = template;