0

我正在使用 ajaxify.js ( https://github.com/browserstate/ajaxify/blob/master/ajaxify-html5.js ) 来加载页面内容。默认情况下,此脚本从页面异步加载脚本,如下所示:

$scripts.each(function(){
    var $script = $(this), 
        scriptText = $script.text(),
        scriptType = $script.attr('type'),
        scriptId = $script.attr('id');

    scriptNode = document.createElement('script');

    if(scriptType) {
        $(scriptNode).attr('type', scriptType);
    }

    if(scriptId) {
        $(scriptNode).attr('id', scriptId);
    }

    scriptNode.appendChild(document.createTextNode(scriptText));
    contentNode.appendChild(scriptNode);
});

问题是对于我的下划线模板, using$script.text()完全忽略了模板的 HTML 内容。

另一方面,使用从模板代码中$script.html()转义<和字符(下划线等......),输出最终看起来像:><%

&lt;% _.each(things,function(thing,key,list){ %&gt;

如何使脚本的内部 html/文本保持完整,以便在 AJAX 负载下正常运行?谢谢!

完整的模板脚本是:

    <script type="text/html" id='furniture-template'>
        <div class="accordion collapse">
            <div class="accordion-group">
                <% _.each(things,function(thing,key,list){ %>

                <div class="accordion-heading">
                    <a class="no-ajaxy accordion-toggle ic-minus block collapsed" data-toggle="collapse" href="#things-<%= thing.slug %>">
                        <%= thing.title %>
                    </a>
                </div> <!-- header -->

                <div id="things-<%= thing.slug %>" class="accordion-body collapse">
                    <div class="accordion-inner">
                        <% for(var item in thing.items) { %>
                        <div class="item">
                            <% if( thing.items[item].images == true ) { %>
                                <a class="no-ajaxy" data-target="<%= thing.items[item].slug %>-gal" class="img-link ic-cam fl" title="View an example"></a>
                            <% } %>

                            <a 
                                class="item-add ic-plus" 
                                data-title="<%= thing.items[item].title %>" 
                                data-slug="<%= thing.items[item].slug %>"
                                data-img="<%= thing.items[item].images %>"
                                data-shorthand="<%= thing.items[item].shorthand %>"
                                data-price="<%= thing.items[item].price %>"
                            >
                                <%= thing.items[item].title %>
                            </a>
                        </div>
                        <% } %>
                    </div> <!-- inner -->
                </div> <!-- accordion-body -->

            <% }); %>
            </div>
        </div>
    </script>
4

2 回答 2

1

好奇的情况。简单的解决方案是使用.html()和取消转义转义的下划线序列,这可能是您想要的(即您可能不想转义所有内容):

$script.html().replace(/&lt;%/gi, '<%').replace(/%&gt;/gi, '%>')
于 2013-06-14T09:32:02.890 回答
0

你没有试过这个:

contentNode.innerHTML = scriptnode;
于 2013-06-14T09:37:03.823 回答