0

我想知道是否可以通过 javascript 执行一个函数,我将编写一个函数将外部 JS 文件的内容写入 html 文件。

就像这样:

    function insertInlineScript (path){
            var readScriptFromPath (path){
            return "<script>" + scriptContents + "</script>";
            }
    }

然后我把它插入我的页面

    insertInlineScript("/path/to/file");
    insertInlineScript("/path/to/file_2");

页面的输出将是

    <script>
            //contents of first file
    </script>
    <script>
            //contents of 2nd file
    </script>
4

1 回答 1

0

您可以使用 HTML5 的新文件 API 来读取文件内容。这是一个使用文件输入的示例,您可以重用代码并自行调整:

<input type="file" id="fileinput" />
<script type="text/javascript">
  function readSingleFile(evt) {
    //Retrieve the first (and only!) File from the FileList object
    var f = evt.target.files[0]; 

    if (f) {
      var r = new FileReader();
      r.onload = function(e) { 
          var contents = e.target.result;
        alert( "Got the file.n" 
              +"name: " + f.name + "n"
              +"type: " + f.type + "n"
              +"size: " + f.size + " bytesn"
              + "starts with: " + contents.substr(1, contents.indexOf("n"))
        );  
      }
      r.readAsText(f);
    } else { 
      alert("Failed to load file");
    }
  }

  document.getElementById('fileinput').addEventListener('change', readSingleFile, false);
</script>

更多信息在这里这里

于 2013-10-14T07:58:22.033 回答