将javascript代码的输出放入文件中

时间:2018-10-24 19:59:31

标签: javascript html5

嗨,我想问一下是否可以将此代码的内容写入文件!原因是当我打开源代码时,我在那里找不到输出

<!DOCTYPE html>
<html>
   <body onload="getLocation()">
      <p></p>
      <p id="demo"></p>
      <script>
         var x = document.getElementById("demo");
         function getLocation() {
             if (navigator.geolocation) {
                 navigator.geolocation.getCurrentPosition(showPosition);
             } else { 
                 x.innerHTML = "Geolocation is not supported by this browser.";
             }
         }

         function showPosition(position) {
         x.innerHTML = "Latitude: " + position.coords.latitude + 
         "<br>Longitude: " + position.coords.longitude;
         } 
      </script>
   </body>
</html>

2 个答案:

答案 0 :(得分:0)

使用此函数将数据和文件名传递给该函数,它将下载

function downloadFile(text, filename) 
{
   var hiddenElement = document.createElement('a');
   hiddenElement.href = 'data:attachment/text,' + encodeURI(text);
   hiddenElement.target = '_blank';
   hiddenElement.download = filename;
   hiddenElement.click();
}

答案 1 :(得分:0)

我用过它,但是我在test1.txt [object HTMLParagraphElement]中得到了这个内容

<script>
var x = document.getElementById("demo");

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } else { 
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}

function showPosition(position) {
    x.innerHTML = "Latitude: " + position.coords.latitude + 
    "<br>Longitude: " + position.coords.longitude;

var hiddenElement = document.createElement('a');
   hiddenElement.href = 'data:attachment/text,' + encodeURI(x);
   hiddenElement.target = '_blank';
   hiddenElement.download = 'test1.txt';
   hiddenElement.click();  

}

</script>