关于实现在博客网站中实时的运行自己的代码
Document
Document运行
要实现代码的运行必要的条件是取到代码,并运行,在textarea中的代码中的> 或< &等都被替换了
所以使用normalizeCode 函数可以是code取出后正常
var normalizeCode = function(code){
code = code.replace(/
code = code.replace(/>/g,‘>‘);
code = code.replace(/&/g,‘&‘);
return code;
};
接下来需要将取出的代码在空白的页面运行
newWin=function(code){
var newwin=window.open("","_blank");//新建一个窗口
newwin.document.open(‘text/html‘, ‘replace‘);//第二个参数只有一个值 可选:replace,如果启用了该值,则新建的文档会覆盖当前页面的文档(相当于清空了原文档里的所有元素,且不能后退即,浏览器的后退按钮不可用);
newwin.opener = null;
newwin.document.write(code);
newwin.document.close();
}
接下来是什么点击什么触发这段代码,在上面的例子中是通过textare中的id 和button 的id达到快速找到要运行的文本和点击运行的按钮打开窗口
window.οnlοad=function(){
document.getElementById("run").οnclick=function(){
var code=document.getElementById("runcode").innerHTML;
code=normalizeCode(code);
newWin(code);
}
}
这个方法比较简单,不适用一个窗口中含有多个运行的html
//2016/8/27
//过两天更新
原文:http://www.cnblogs.com/heyinwangchuan/p/5813042.html