日期:2014-05-16  浏览次数:20371 次

insertAdjacentHTML奇怪问题
看下面的两段代码:

代码一:

<DIV   ID= "ScriptDiv "> 3 </Div>

<script   type= "text/javascript ">

var   sHTML= " <input   type=button   onclick= "   +           "go2() "   +   "   value= 'Click   Me '> <BR> "
            var   sScript= ' <SCRIPT   DEFER> '
            sScript   =   sScript   +           'function   go2(){   alert( "Hello   from   inserted   script. ")   } '
            sScript   =   sScript   +   ' </script '   +   '> ';
            document.all[ "ScriptDiv "].insertAdjacentHTML( "afterBegin ",sHTML   +   sScript);


</script>


代码二:

<DIV   ID= "ScriptDiv "> </Div>

<script   type= "text/javascript ">

var   sHTML= " <input   type=button   onclick= "   +           "go2() "   +   "   value= 'Click   Me '> <BR> "
            var   sScript= ' <SCRIPT   DEFER> '
            sScript   =   sScript   +           'function   go2(){   alert( "Hello   from   inserted   script. ")   } '
            sScript   =   sScript   +   ' </script '   +   '> ';
            document.all[ "ScriptDiv "].insertAdjacentHTML( "afterBegin ",sHTML   +   sScript);


</script>


代码一与代码二的区别仅在于 <div> 里面是否有文本,有的话,insertAdjacentHTML则工作正常   ,若没有,则insertAdjacentHTML工作不正常(根本就没有将HTML插入),请问这是什么原因?



------解决方案--------------------
<body>
<DIV ID= "ScriptDiv "> 3 </Div>
<script type= "text/javascript ">

var sHTML= " <input type=button onclick= " + "go2() " + " value= 'Click Me '> <BR> "
var sScript= ' <SCRIPT DEFER> '
sScript = sScript + 'function go2(){ alert( "Hello from inserted script. ") } '
sScript = sScript + ' </script ' + '> ';
document.all[ "ScriptDiv "].insertAdjacentHTML( "afterBegin ",sHTML + sScript);
alert(document.body.innerHTML);
</script>
</body>


<body>
<DIV ID= "ScriptDiv "> </Div>
<script type= "text/javascript ">
var sHTML= " <input type=button onclick= " + "go2() " + " value= 'Click Me '> <BR> "
var sScript= ' <SCRIPT DEFER> '
sScript = sScript + 'function go2(){ alert( "Hello from inserted script. ") } '
sScript = sScript + ' </script ' + '> ';
document.all[ "ScriptDiv "].insertAdjacentHTML( &