Research on how to apply script when specifying innerHTML in AJAX

Time:2022-6-14

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

<html>
<head>
<script type=”text/javascript”>
<!–
function load1(){
var Content= document.getElementById(“Content”);
alert(“load1”);
}
function load2(){
var Content= document.getElementById(“Content”);
Content.innerHTML=”load2:<script>load1();<\/script>”;
}

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>”;
Content.innerHTML=str;
var regExp=/<script.*>(.*)<\/script>/gi;
if(regExp.test(Content.innerHTML)){
eval(RegExp.$1);
}

////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);
//if(matchArray){
//    for(var i=0;i<matchArray.length;i++){
//        if(regExp.test(matchArray[i])){
//            alert(RegExp.$1);
//        }
//        else{
//          alert(matchArray[i]);
//        }
//    }
//}

}

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

 

[description]

load1

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]