问题连接:http://www.cnblogs.com/uedt/articles/1718341.html弄了一个运行代码框玩,可是发现点击按钮时onload事件不触发,但是每次刷新都会触发,只是第一次加载不会。网上搜索未果,然后又自己写了一个demo,将代码框上的代码复制到demo上,发现点击后可以alert了,难道说跟博客本身的体制有关,请教各位,问题困扰很久了,谢谢
下面是自己写的demo,把代码放入可正常运行
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript">// <![CDATA[
    //运行文本域代码
    function runEx(cod1) {
        cod = document.all(cod1)
        var code = cod.value;
        if (code != "") {
            var newwin = window.open('', '', ''); //打开一个窗口并赋给变量newwin。
            newwin.opener = null // 防止代码对论谈页面修改
            newwin.document.write(code); //向这个打开的窗口中写入代码code,这样就实现了运行代码功能。
            newwin.document.close();
        }
    }
// ]]></script>
</head>
<body>
    <p><textarea name="textarea" cols="100" rows="25" id="rn01"></textarea><br />
    <input type="button" value="运行代码" onclick="runEx('rn01')" style="cursor: hand;" /> 
    [Ctrl+A 全部选择 提示:你可先修改部分代码,再按运行] </p>
</body>
</html>

解决方案 »

  1.   

    刷新肯定会调用onload,但是点击的话有的浏览器是不支持这种写法的,楼主可以换成其他函数来调用,浏览器存在差异
      

  2.   


    补充一点 ,我在自己的demo上运行是正常的,也是通过click
      

  3.   

    谢谢回复
    要如何才能把代码写到打开的窗口里面呢,你是说window.open吗
      

  4.   

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title></title>
        <script type="text/javascript">// <![CDATA[
        //运行文本域代码
        function runEx(cod1) {
            if (code != "") {
                var newwin = window.open('', '_blank', ''); //打开一个窗口并赋给变量newwin。
    newwin.document.open('text/html', 'replace');
    var code=document.getElementById(cod1).value;
               // newwin.opener = null // 防止代码对论谈页面修改
                newwin.document.write(code); //向这个打开的窗口中写入代码code,这样就实现了运行代码功能。
                newwin.document.close();
            }
        }
    // ]]></script>
    </head>
    <body>
        <p><textarea name="textarea" cols="100" rows="25" id="rn01"></textarea><br />
        <input type="button" value="运行代码" onclick="runEx('rn01')" style="cursor:hand;" /> 
        [Ctrl+A 全部选择 提示:你可先修改部分代码,再按运行] </p>
    </body>
    </html>