javascript in innerhtml not working

人盡茶涼 提交于 2019-12-13 08:30:24

问题


For example:

<html>
    <div id="media">123</div>
    <a href="javascript:void(0)" onClick="return fun()">Click</a>
    <script type="text/javascript">
        function fun() {
            document.getElementById("media").innerHTML = '<script type="text/javascript">alert("working");<\/script>';
        }
    </script>
</html>

After you click the alert does not show.

alert("working"); is just an example. I want it to finish one job other javascript . I have a job to be processed through ajax should have used innerHTML


回答1:


The HTML spec specifies that script tags inserted using innerHTML should not be executed. This is a security consideration.

There are still ways to do this if you are determined, such as adding it to img handlers or creating a script element, inserting it into the DOM and changing its text property. I will not elaborate on these, since doing this is generally considered somewhat sketchy. If you are not trying to inject script, you should include the script element in the page source.




回答2:


<script type="text/javascript">

function fun() {
    alert("working");
}
</script>

<div id="media">123</div> <a href="javascript:void(0)" onClick="fun();">Click</a>



回答3:


Your JS function should be like this.

function fun() {
  alert("working");
}


来源:https://stackoverflow.com/questions/15417839/javascript-in-innerhtml-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!