我正在编写一个 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(", ") + " }";
};
关于javascript - 如何将我的 javascript 代码输出为 HTML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14867828/