问题描述:

I was wondering how to run JS code posted by a user in the TextArea when he presses button without refreshing the entire page. I want to have a canvas, a TextArea and a button. When the button is pressed, it runs code from the TextArea and then paints stuff on the canvas.

I know how to put the posted code into variable string.

What I don't know is how to run code in that string.

网友答案:

You should be able to wrap code in eval() function. It evaluates JavaScript code represented as a string.

Example:

eval(new String("2 + 2")); // returns a String object containing "2 + 2"
eval("2 + 2");             // returns 4

In your case you will need to read code from text area and pass it to eval() it could look something like this:

eval(document.getElementById('textareaid').value);
网友答案:

If it is HTML just send it to a variable with a submit button and than document.write("variable").

相关阅读:
Top