Research on how to apply script when specifying innerHTML in AJAX


In fact, this article has nothing to do with Ajax, but it is a problem encountered in Ajax projects So During innerHTML assignment, the script will not be run. You can use regular expressions to extract the script, and then Eval (script);

Sample code

<script type=”text/javascript”>
function load1(){
var Content= document.getElementById(“Content”);
function load2(){
var Content= document.getElementById(“Content”);

function load3(){
var Content= document.getElementById(“Content”); 

//Why JavaScript must be followed by a valid text tag? Let’s talk about the difference between JS in IE and Firefox In script script block

//If there is no valid text tag before, ie will make an error But Firefox works. God, help ie
Var str= “<a>javascript must be after a valid text tag </a><script type=\” text/javascript\ “>load1(); <\/script>”;
var regExp=/<script.*>(.*)<\/script>/gi;

////The following code is set to match multiple script blocks, but unfortunately it cannot be used in IE

////It can only run on Firefox. Because it’s enough, it can’t be written down. If you are interested, you can complete it. I didn’t learn JS well
//var matchArray=str.match(regExp);
//    for(var i=0;i<matchArray.length;i++){
//        if(regExp.test(matchArray[i])){
//            alert(RegExp.$1);
//        }
//        else{
//          alert(matchArray[i]);
//        }
//    }


<div id=”Content”>
<input type=”button” onclick=”javascript:load1();” value=”load1″/>
<input type=”button” onclick=”javascript:load2();” value=”load2″/>
<input type=”button” onclick=”javascript:load3();” value=”load3″/>




Of course it works

In load2

Content. When innerHTML is assigned, the script in it will not be run

In load3

Get the script block in innerHTML and eval it before normal operation

Please mail to me [email protected]