Does this not work because I can't use a script in a div?

霸气de小男生 提交于 2019-12-11 20:28:07

问题


I am making a website with a program editor, for users to make HTML programs. I usually test this out by inputting <script> alert("Hi!"); </script> into the body input area, but no alert comes. As you can see from the code, the result is the script ending up inside the div. So do scripts work in divs? If they do, here's my code (the important part, at least):

This is my script to run when I press the "Run!" button:

<script>
    function onclick(){
        document.getElementsByTagName("head")["0"].innerHTML += eval(document.getElementById("editorHead").value);
        document.getElementById("result").innerHTML = eval(document.getElementById("editorBody").value);
    }
</script>

This is the code for the input areas & run button (omitting the text between them & class attributes):

<textarea id="editorHead" rows="20"></textarea>
<textarea id="editorBody" rows="20"></textarea>
<div id="result"></div>
<button onclick="onclick();">Run!</button>

I tried changing the onclick's name to run, and that made the clicking work (before that the button wouldn't turn blue when you clicked it), but that was it.


回答1:


The asked question is do scripts work in div's. Yes <script></script> tag content executes inline where it appears in the document.

However, it always executes in the document context. Meaning this === document. So to bind to the div's onclick method (the way you handle ui events in javascript) you need to find the div :

document.findElementById("my-div-id").onclick = function(e) {
   // do something
};

Note this clobbers the default behavior for the element if there is a default click behavior (like on an a tag)

Also to be more clear on the expected behavior. Do this

<script>
    function doSomething() {
        alert();
    }
</script>
<button onclick="doSomething()">Button</button>


来源:https://stackoverflow.com/questions/19963781/does-this-not-work-because-i-cant-use-a-script-in-a-div

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