Jump to content

Displaying code?


davej

Recommended Posts

Is there a better way to do this?

<!DOCTYPE html><html><head><title>Local Variables</title><style>#out{color: green;font-weight: bold;background-color: #ccc;}</style><script>var count = 555;window.onload = init;function init(){var txtstr2 = txtstr.replace(/;/g,";<br/>").replace(/{/g,"{<br/>").replace(/function/g,"<br/>function");document.getElementById('out').innerHTML = txtstr2;eval(txtstr);}var txtstr = "document.getElementById('btn1').onclick = mpp;var count = 777;function mpp(){  var count = 0;  alert('init func: count=' + count);  return pp();  function pp(){    count++;    alert('func: count=' + count);  }}//end func mpp";</script></head><body><p>Click the button to see an alert displaying the variable value</p><input type="button" id="btn1" value="Run"/><p>Notes: this is not a closure. The internal variable is not preserved.</p><p>Code:</p><div id="out"></div><br/><br/><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures">Mozilla Closures</a><br/><a href="http://en.wikipedia.org/wiki/Closure_%28computer_science%29">Wikipedia Closure</a></body></html>
Link to comment
Share on other sites

Well, I want to execute the same code that is displayed. To use eval() I need a string, but strings seem to exclude newlines. I can almost certainly insert newlines into a string, but at what points, if I've already lost their position? Is there another approach?

Edited by davej
Link to comment
Share on other sites

Well... this works ok...

var txtstr = "document.getElementById('btn1').onclick = mpp;nvar count = 777;nnfunction mpp(){n  var count = 0;n  alert('init func: count=' + count);n  return pp();nn  function pp(){n    count++;n    alert('func: count=' + count);n  }n}//end func mpp";

...if I dump it into a textarea to display it or if I replace the newlines with br I can dump it into a div. If I instead enter it as the default text in the textarea and then read it out that works fairly smoothly and does not require any character additions or replacements.

Edited by davej
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...