javascript 将javascript编写为document.getElementById函数的innerHTML

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16657190/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 05:31:49  来源:igfitidea点击:

Write javascript as innerHTML of document.getElementById function

javascripthtmlinnerhtml

提问by Hamzah Malik

i dont know a lot of javascript but one thing ive realized is doing this

我不知道很多 javascript 但我意识到的一件事就是这样做

function example()
{
document.getElementById("example").innerHTML="<script>document.write(example)</script>"
}

doesnt work! i understand this but is there another way of doing this same thing that does work?

不工作!我明白这一点,但有没有另一种方法可以做同样的事情?

回答by BBog

This approach worked for me:

这种方法对我有用:

<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>

Edit: I've found more info about your problem here, I suggest you read the question, it has plenty of helpful answers and it also explains why your first approach did not work: Can scripts be inserted with innerHTML?

编辑:我在这里找到了关于你的问题的更多信息,我建议你阅读这个问题,它有很多有用的答案,它还解释了为什么你的第一种方法不起作用:可以用innerHTML插入脚本吗?

A simple vanilla approach of using this code to write data inside a div after the page has loaded could be done like this:

在页面加载后使用此代码在 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>

回答by Cem Demir

There is two error on your script. This is doesn't work, because variable name and function name equal to div id and this wrong method for javascript. You write a code to your div, but you don't run it. You can try that;

您的脚本有两个错误。这是行不通的,因为变量名和函数名等于 div id 和这个错误的 javascript 方法。你给你的 div 写了一段代码,但你没有运行它。你可以试试;

<div id="mydiv"></div>
<script>
function example()
{
document.getElementById("mydiv").innerHTML = eval("document.write('lololo')");
}
example();
</script>