在javascript <script>标记内找到一个jquery对象

Raj*_*jat 6 html javascript jquery

我在以下HTML页面中有一个脚本:

<script id="scriptid" type="text/html">
    <div id="insidedivid">
        ... html code ...
    </div>
</script>
Run Code Online (Sandbox Code Playgroud)

我能够得到HTMLScriptElement使用$("#scriptid")但我无法获得具有id的底层div对象"insidedivid".这样做的方法是什么?

Ell*_* B. 8

这是不可能的; 浏览器不会将<script>标记内的HTML内容视为DOM的一部分.当您检索<script>标记的内容时$('#idhere').html(),您将获得字符串结果.

为了回答Troy的问题,他最有可能在<head>他的文档中包含模板,这样他最终可以在浏览器端动态呈现内容.但是,如果是这种情况,OP应使用不同的MIME类型text/html.您应该使用未知的MIME类型,例如 - text/templates使用text/html混淆内容的目的.

你试图进入<script>标签并抓住一个div原因是因为你在单个<script>标签内构建了较小的子模板.那些较小的模板应该放在它们自己的<script></script>标签中,而不是包含在一个大的<script></script>标签对中.

所以,而不是:

<script type="text/template" id="big_template">
    <div id="sub_template_1">
        <span>hello world 1!</span>
    </div>
    <div id="sub_template_2">
        <span>hello world 2!</span>
    </div>
</script>
Run Code Online (Sandbox Code Playgroud)

做这个:

<script type="text/template" id="template_1">
    <span>hello world 1!</span>
</script>

<script type="text/template" id="template_2">
    <span>hello world 2!</span>
</script>
Run Code Online (Sandbox Code Playgroud)