2015-06-19 660 views
2

现在我试图使用javascript和FileSaver.js包将信息从我正在创建的HTML页面保存到文本文档中。我对HTML不是很熟悉,而且对JavaScript来说是全新的,所以很可能是我犯了一些极其严重的错误。目前,我将eligrey的FileSaver.js文件放在与我工作的HTML文件相同的目录中,所以我应该能够简单地将它称为HTML中的“FileSaver.js”。将FileSaver.js saveAs()函数实现为HTML脚本

现在我从做某件事情是这样的:

//some irrelevant text 
 

 
<script src="FileSaver.js"> 
 
    function download(){ 
 
    
 
    //alert("hello world"); 
 
    //this alert line was to test the function call 
 
    //the alert actually appears when the <script> tag 
 
    // has no src field labeled. Just an observation. 
 
    
 
    var blob = new Blob(["Hello World"],{type:"text/plain;charset=utf-8"}); 
 
    saveAs(blob,"helloworld.txt"); 
 
    } 
 
</script> 
 

 
//some more irrelevant text 
 

 
<input type="button" value="download" onclick="download();"/> 
 
/*from this button I want to gather information from input text fields on the page. 
 
I already know how to do that, the problem is creating and, subsequently, 
 
downloading the text file I am trying to create. For simplicity's sake, the text I am 
 
capturing in this example is hardcoded as "hello world"*/ 
 

 
//last of irrelevant text 
 
//oh, and don't try to run this snippet :P

我也有可用的eligrey的Blob.js文件在我眼前的工作目录为好,以防万一。

截至目前,按钮什么都不做。我确信我正在调用该函数,因为我可以收到JavaScript警报文本,至少在脚本标记没有src时。如果我添加一个src,绝对没有任何反应。我正在测试的浏览器是Windows XP上的最新Google Chrome稳定版本(我认为是43.0)。请告诉我任何我失踪和/或做错的事情。在此先感谢

回答

1

您不能在标记中包含src属性和内容的脚本标记。将它分成两个独立的脚本标记。见What if script tag has both "src" and inline script?

注意<script>cannot be a self-closing tag

<script src="FileSaver.js"></script> 
<script> 
    function download(){ 

    //alert("hello world"); 
    //this alert line was to test the function call 
    //the alert actually appears when the <script> tag 
    // has no src field labeled. Just an observation. 

    var blob = new Blob(["Hello World"],{type:"text/plain;charset=utf-8"}); 
    saveAs(blob,"helloworld.txt"); 
    } 
</script> 
+0

感谢你,因为你写它的实际工作!我已经尝试过,但没有工作,所以有点奇怪,关闭它就好。哦,好的,再次感谢! – MasterChef

+0

是的,这是另一回事,脚本标签不能像自动关闭一样,就像divs一样,只有特定的标签才能自动关闭;)http://stackoverflow.com/questions/69913/why-dont-self-closing -script-tags-work通常只有不能有任何内容的标签才能自动关闭,比如'input,br,img ...' –