如何将javascript代码输出到HTML?
我正在完成一个javascript组件的编写,我想提供一组示例来说明配置属性、事件、方法等 我目前使用以下HTML来记录单个属性:如何将javascript代码输出到HTML?,javascript,jquery,html,eval,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="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);
});
$('.conf.opt-ex')。单击(函数(){
var raw=$(this.next().html();
var rawCfg=JSON.parse(原始);
var exId='example-'+$('div[id^=“example-”).length+1;
var cfg=$.extend({
renderTo:$('#'+exId),
宽度:590
},rawCfg);
$('',{id:exId}).insertBefore(this);
新霉素组分(cfg);
});
这一切都很顺利。。。棘手的部分来了。我希望将完整的计算代码作为原始HTML输出到组件的正上方。我想向用户显示的是:
<code><pre>
new MagicSuggest({
renderTo: $('#example-1'),
width: 590,
allowFreeEntries: false
});
</pre></code>
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(", ") + " }";
};
新魔法建议({
renderTo:$(“#示例-1”),
宽度:590,
allowFreeEntries:false
});
我做了一些实验,但它们看起来都很笨拙。有什么建议吗
非常感谢 据我所知,您正试图在新MagicSuggest字符串中打印对象的值。好的,您只需要使用字符串append来附加它。 对于打印对象本身,可以使用
参考资料:在我看来它并不笨拙。。。您有什么特别的问题吗?问题是如何输出前两个部分的最后一个代码部分?如果所有值都是常量,而不是像$(“#示例-1”)这样的函数调用,那么JSON.stringify将起作用