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

标签 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>

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

非常感谢!

最佳答案

据我了解,您正在尝试在新的 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/

关于javascript - 如何将我的 javascript 代码输出为 HTML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14867828/

相关文章:

javascript - 组合对象和数组

javascript - 如何使用 ng-repeat 显示来自 API 的所有值,其中我只需要显示所有对象中的一个键值?

javascript - Express 中间件适用于所有方法,而不是 Controller 中定义的方法

javascript - 如何淡入标题中的所有元素?

html - 如何使右侧边栏悬停在页面上下文上而不是占用单独的空间

php - 当 url 有 & 时,file_get_contents 失败

javascript - jQuery,通过单击选择一个元素

javascript - 使用 jquery 设置 MVC CheckBoxFor 值

javascript - 通过 AJAX 的 PHP 请求失败

html - 使用 Ruby Mechanize 解析结构不良的 HTML 文档