简体   繁体   中英

Multiple JavaScript functions not running

I'm trying to make an app that allows you a text editor. You can type anything in to a text block. You can do two things with said text block:
a) run the text as an html page in a new about:blank tab or
b) save the text as a.html
For some reason, though, when I tried to implement the save ability, neither function would load. If I go into the JS console, it shows me this error upon clicking on the save button:

"Uncaught ReferenceError: saveAsFile is not defined (temp.html,1)"

When I seperated them into two <script> blocks, I could get the save function to work. However, when I did that, the Run in New Tab function no longer worked. It was utterly confusing.
I have used multiple functions before, and I don't know why it's suddenly not working. Can someone help? This is my code:

<script>
function run() {
var codeTab = window.open("" _blank);
var codeRun = document.getElementById("code").value;
codeTab.document.write(codeRun);
}
</script>
<script>
/*i stole-i mean used-this code from someone else*/
function saveAsFile() {
var textToSave = document.getElementById("code").value;

var hiddenElement = document.createElement('a');

hiddenElement.href = 'data:attachment/text,' + encodeURI(textToSave);
hiddenElement.target = '_blank';
hiddenElement.download = 'save.html';
hiddenElement.click();
}
</script>

On line 3, you have window.open("" _blank); . It should be window.open("_blank"); .

I also cannot see anywhere saveAs() is being called (or defined). Is it possibly being called in codeRun ? See below code which worked for me.

<textarea id="code">

</textarea>
<button onclick="run();">Run</button>
<button onclick="saveAsFile();">Save</button>

<script>
  function run() {
    var codeTab = window.open("_blank");
    var codeRun = document.getElementById("code").value;
    codeTab.document.write(codeRun);
  }

  /*i stole-i mean used-this code from someone else*/
  function saveAsFile() {
    var textToSave = document.getElementById("code").value;

    var hiddenElement = document.createElement('a');

    hiddenElement.href = 'data:attachment/text,' + encodeURI(textToSave);
    hiddenElement.target = '_blank';
    hiddenElement.download = 'save.html';
    hiddenElement.click();
  }
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM