我不太了解 JavaScript,但我意识到的一件事就是这样做
function example()
{
document.getElementById("example").innerHTML="<script>document.write(example)</script>"
}
不起作用!我理解这一点,但是还有另一种方法可以做同样的事情吗?
最佳答案
这种方法对我有用:
<body>
<div id="main">
</div>
<script>
// create a script element
var script = document.createElement('script');
// fill its inner html with js code
script.innerHTML = 'alert("Javascript");'
// add it inside your target div and then profit!
document.getElementById('main').appendChild(script);
</script>
</body>
编辑: 我在这里找到了有关您问题的更多信息,我建议您阅读这个问题,它有很多有用的答案,它还解释了为什么您的第一种方法不起作用:Can scripts be inserted with innerHTML?
在页面加载后使用此代码在 div 内写入数据的简单方法可以如下完成:
<html>
<head>
<script>
window.onload = function () {
var script = document.createElement('script');
script.innerHTML = 'alert("Javascript");'
document.getElementById('main').appendChild(script);
}
</script>
</head>
<body>
<div id="main">
</div>
</body>
</html>
关于javascript - 将 javascript 编写为 document.getElementById 函数的innerHTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16657190/