Dynamically writing and evaluating a <script>
I want to dynamically write (and have evaluated) a script I write to a tag. Why won't this code work?
<html>
<head>
<script id="cojs">
</script>
<script type="text/javascript">
document.getElementById('开发者_如何学编程cojs').innerHTML = 'alert("hey");';
</script>
</head>
<body>
</body>
</html>
Well script tags are evaluated when they are parsed. So since the section above is not parsed anymore after you alter it, it doesn't work.
If your usecase allows it try the eval function:
<html>
<head>
<script type="text/javascript">
eval('alert("hey");');
</script>
</head>
<body>
</body>
</html>
If you want a script to be interpreted you need to add it to the document. Some browsers don't use innerHTML for scripts, but all will set a script's text property.
<!doctype html>
<html lang= "en">
<head>
<meta charset= "utf-8">
<title> title</title>
<script>
window.onload=function(){
var head=document.getElementsByTagName('head')[0],
who= document.createElement('script');
who.text= 'alert("hey");';
head.appendChild(who);
}
</script>
</head>
<body>
</body>
</html>
精彩评论