0

编辑:为了清晰和实际使用而进行编辑。实际使用甚至可能使这种情况变得更容易?

我正在构建一个样式指南,我想为将使用该指南的人包含常见样式/模式的源代码。我的计划是将所有繁重的 HTML 代码模块抽象到外部文件中,并使用 jQuery 将它们拉入,然后使用SyntaxHighlighter突出显示屏幕上显示的内容。下面的 HTML 显示了我的意图和我想做的事情。

我现在已经删除了所有 JavaScript,因为它不会为手头的问题增加任何价值。我会更新我想出的任何东西。

<div class="sg-section">
    <div class="sg-section-body">
        <div data-load="markup/pagination.html"></div>
    </div>
    <div class="sg-section-code">
        <small>Source Code</small>
        <pre class="brush: js">
            <!-- This is where I want to print out the contents  -->
            <!-- of the 'sg-section body' above and show it's source -->
        </pre>
    </div>
</div>

我可以用一个简单的$('[data-load]'.each();语句来加载数据,但是我很难将结果打印出来sg-section-code并突出显示。

结论:切换到Prism。工作精美。

4

2 回答 2

1

Edited:

  function loadScript(placeholder){
    var $p = $(placeholder);
    var deferred = $.Deferred();
    $p.load($p.attr('data-load'),function(response){
        $p.parent().append(response).end().remove();   
        deferred.resolve();
    });
    return deferred;
} 

to remove the placeholder and insert your code from external html directly, this should solve your problem that only display the placeholder instead of real code.

your problem is that load is an async method, and you don't know when to call SyntaxHighlight.all();

so, the solution come into my head is use jQuery.Deferred object. let load tell you when it fininsh loading all external scripts.

first extract the method loadScript

function loadScript(placeholder){
  var $p = $(placeholder);
  var deferred = $.Deferred();
  $p.load($p.attr('data-load'),function(){
    deferred.resolve();
  });
  return deferred;
}

then push all the task into an array, finally use $.when().then() to notify when all the script has been loaded, then call SyntaxHighlighter.all();

$(function(){
  var q = [];
  $('[data-load]').each(function(item){
    q.push(loadScript(item));
  });
  $.when.apply($, q).done(function(){
    SyntaxHighlighter.all();
  });
});
于 2014-02-08T02:16:03.493 回答
0
$(document).ready(function(){

    // Get Markup Pages
    $("[data-load]").each(function (index) {
        $(this).load($(this).attr("data-load"),function(){SyntaxHighlighter.all()});
    });
});

这应该可以工作,就像SyntaxHighlighter.all();在加载 test.html 后执行的那样

于 2014-02-08T03:30:38.417 回答