如何将我的javascript代码输出到HTML?

时间:2013-02-14 04:30:59

标签: javascript jquery html eval

我最后编写了一个javascript组件,我想提供一些示例来说明配置属性,事件,方法等......

我目前有以下HTML来记录单个属性:

      <div class="conf">
        <div class="opt-name">allowFreeEntries</div>
        <code>boolean</code>
        <div style="clear:both;"></div>
        <div class="opt-desc">Restricts or allows the user to validate typed entries.<br/>Defaults to <em>true</em>
            <a class="opt-ex">View an example</a>
            <span class="hidden">{"allowFreeEntries": false}</span>
        </div>
      </div>

当点击“查看示例”链接时,我弹出另一个包含我的组件的div,其默认配置与隐藏范围中给出的自定义配置混合:

$('.conf .opt-ex').click(function(){
    var raw = $(this).next().html();
    var rawCfg = JSON.parse(raw);
    var exId = 'example-' + $('div[id^="example-"]').length + 1;
    var cfg = $.extend({
        renderTo: $('#' + exId),
        width: 590
    }, rawCfg);
    $('<div/>',{id: exId}).insertBefore(this);
    new MyComponent(cfg);
});

这一切都很顺利......这是棘手的部分。我想在组件上方输出完整的评估代码作为原始HTML。我想向用户显示的是:

        <code><pre>
        new MagicSuggest({
            renderTo: $('#example-1'),
            width: 590,
            allowFreeEntries: false                    
        });
        </pre></code>

我做了一些实验,但它们看起来都很笨拙。有什么建议吗?

非常感谢!

1 个答案:

答案 0 :(得分:0)

根据我的理解,您试图在新的MagicSuggest字符串中打印对象的值。 AFAIK你只需使用字符串追加即可。 要打印对象本身,您可以使用

   var printObj = typeof JSON != "undefined" ? JSON.stringify : function(obj) {
     var arr = [];
     $.each(obj, function(key, val) {
     var next = key + ": ";
     next += $.isPlainObject(val) ? printObj(val) : val;
     arr.push( next );
     });
     return "{ " +  arr.join(", ") + " }";
   };

参考:http://api.jquery.com/jQuery.extend/