JavaScript JSzip将文件添加到每个循环

javascript jszip add file to each loop

本文关键字:循环 添加 JSzip 文件 JavaScript      更新时间:2023-09-26

您好,我在使用 jszip 的循环时遇到问题 -这是为了替换文本,我打算做 1000 个文件或更多。我想要的是为每个添加数字 i++ 并将其保存到 zip 中的单独文本文件中。但是现在我的代码是这样的,它只显示带有输入文本的最后一个文件 - 请帮助

我希望 zip.add 遍历每个变体 - 但它只写入数字而不是整个输入+数字

.HTML:

<script type="text/javascript" src="jszip.js"></script>
<form>
<label> Enter Block of text </label>
<textarea id="inp" name="original"></textarea>
<label> Here is your result </label> 
<textarea id="out" name="result"></textarea>
<label> Enter string to replace </label> <br>
<input type="text" id="ori" name="string"></input>
<label> Enter what to replace it with </label> 
<input type="text" id="new" name="replace"></input>
<input type="button" onClick="getin()" value="Click for result">
<input id="button" type="button" onClick="getzip()" value="Create Zip">    </input> </form>

JAVASCRIPT:

var zip = new JSZip();
for (var i = 1; i < 100; i++) {
    getin(i) 
    }
function getin() {
    var old = document.getElementById("ori").value;
    var reg = new RegExp(old, "gim" );
    var e = document.getElementById("new").value;
    var str1, str2;
    str1 = document.getElementById("inp").value;
    if (str1 == "") {null;}
    var end = str1.replace (reg, e+i);
    document.getElementById("out").value = end;
     zip.add("output"+i+".txt", end+"'n")
    }
    function getzip ()     {
    content=zip.generate();
    location.href="data:application/zip;base64,"+content;   
}

这将创建一个包含 100 个文件的 zip,这些文件根据您的正则表达式替换具有不同的输出 - 不确定您希望内容发生什么。

var zip;
function getin() {
  var old = document.getElementById("ori").value;
  var reg = new RegExp(old, "gim");
  var e = document.getElementById("new").value;
  var str1, str2;
  str1 = document.getElementById("inp").value;
  if (str1 == "") {
    return;
  }
  
  zip = new JSZip();
  var result = '';
  
  Array(100).fill().forEach(function(v,i) {  
  	var end = str1.replace(reg, e + i);
  	result += end;
  	zip.file("output" + i + ".txt", end + "'n")
  });
  
  document.getElementById("out").value = result;
}
function getzip() {
  if (!zip) { return; }
  content = zip.generate();
  location.href = "data:application/zip;base64," + content;
}
<script src="http://rawgit.com/Stuk/jszip/master/dist/jszip.min.js"></script>
<form>
  <label> Enter Block of text </label>
  <textarea id="inp" name="original"></textarea>
  <label> Here is your result </label>
  <textarea id="out" name="result"></textarea>
  <label> Enter string to replace </label>
  <br>
  <input type="text" id="ori" name="string">
  <label> Enter what to replace it with </label>
  <input type="text" id="new" name="replace">
  <input type="button" onClick="getin()" value="Click for result">
  <input id="button" type="button" onClick="getzip()" value="Create Zip">
</form>