开发者

Execute dynamic HTML/JavaScript

开发者 https://www.devze.com 2023-03-06 02:36 出处:网络
I\'d like to create a textarea and a division so that whatever embed code you put in the textarea it gets executed on the division in real-time.

I'd like to create a textarea and a division so that whatever embed code you put in the textarea it gets executed on the division in real-time.

Your kind help is greatly appreciated!

JavaScript newbie

Here's an attempt:

<script type="text/javascript">
var X = " HTML or JavaScript "
window.onload=function()
{
document.getElementById("result").innerHTML = document.getElementById("input").value;
}
</script>

<textarea id="input" cols="35" rows="7"> X </textarea>

开发者_运维百科<div id="result"></div>


This will evaluate the contents of the textarea when you click anywhere outside of the textarea. (Code updated to set result from source (<textarea/>) as HTML if source begins with a less-than ('<') or the result of evaluating source as Javascript.)

<textarea id="js" onBlur="run(this)"></textarea>

<div id="result">Result goes here!</div>

<script type="text/javascript">

  function run(elt){
    var target_div=document.getElementById('result'),
        result='';

    if(target_div) {
      if(elt.value.match(/^\s*</)) { // content of textarea begins with less-than
        result=elt.value;
      }
      else { // eval content of textarea as Javascript
        try {
          result=eval(elt.value);
        }
        catch (e) {
          alert('failed to eval source:'+e.description);
        }
      } // else match
      if(result) {
        target_div.innerHTML=result;
      }
    } // if target_div
    return false;
  } // end run
</script>

Of course it's usually considered a VERY BAD IDEA to allow a user to execute arbitrary code. ;-)


Check out Eval()

Here is some code to get you started.

 <textarea id='js'>window.alert('Hello Cruel World');</textarea> <input type=submit onclick="run()" value="run">
 <script>
 function run ()
 {
      eval(document.getElementById('js').value);
 }
 </script>
0

精彩评论

暂无评论...
验证码 换一张
取 消