问题在代码的注释里:
<!DOCTYPE html>
<html>
<head>
<title>Dynamic Script Example 2</title>
</head>
<body>
<p>You should see an alert saying "hi" after clicking the button.</p>
<input type="button" value="Add Script" onclick="addScript()">
<script type="text/javascript">
function loadScriptString(){
var script = document.createElement("script");
var code="function sayHi(){alert('hi');}";
script.type = "text/javascript";
try {
script.appendChild(document.createTextNode(code));
} catch (ex){
script.text = "code";//就是这一行里的"code",
//这里为什么不是字面上的code,
//而是function sayHi(){alert('hi');}?
//感觉反直觉。
//试了下script.text = code;也是可以的。
}
document.body.appendChild(script);
}
function addScript(){
loadScriptString();
sayHi();
}
</script>
</body>
</html>
慕容3067478
相关分类