javascript jszip将文件添加到每个循环

时间:2016-03-01 11:15:35

标签: javascript loops for-loop text jszip

你好,我的循环使用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;   
}

1 个答案:

答案 0 :(得分:0)

这将创建一个包含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>