admin管理员组

文章数量:1415460

I'm trying to save all the link strings into a text document, but it only saves the last link in the document (in this case Youtube).

I want it to save all the links to the saved txt document, what am I doing wrong?

/

var links = document.querySelectorAll('a');

// Loop through all links
 for (var i = 0; i < links.length; i++) {

// Store links in variable
var linksArray = links[i];

// Works fine in console
   console.log(linksArray);
 }


 // Create text document — only saves 1st link in text doc
 var textDoc = document.createElement('a');

 textDoc.href = 'data:attachment/text,' + encodeURI(linksArray);
 textDoc.target = '_blank';
 textDoc.download = 'myFile.txt';
 textDoc.click();

Can someone help me out here? Thank you! :-)

I'm trying to save all the link strings into a text document, but it only saves the last link in the document (in this case Youtube.).

I want it to save all the links to the saved txt document, what am I doing wrong?

https://jsfiddle/zfL2hzvp/4/

var links = document.querySelectorAll('a');

// Loop through all links
 for (var i = 0; i < links.length; i++) {

// Store links in variable
var linksArray = links[i];

// Works fine in console
   console.log(linksArray);
 }


 // Create text document — only saves 1st link in text doc
 var textDoc = document.createElement('a');

 textDoc.href = 'data:attachment/text,' + encodeURI(linksArray);
 textDoc.target = '_blank';
 textDoc.download = 'myFile.txt';
 textDoc.click();

Can someone help me out here? Thank you! :-)

Share Improve this question asked May 29, 2016 at 13:02 CapaxCapax 2252 silver badges13 bronze badges 1
  • 1 Your code overwrites the value of linksArray on each iteration. That's what an = assignment does: replace the former value of a variable with a new value. – Pointy Commented May 29, 2016 at 13:03
Add a ment  | 

1 Answer 1

Reset to default 6
(function() {


  var links = document.querySelectorAll('a');

  var linksArray = [];
  // Loop through all links
  for (var i = 0; i < links.length; i++) {

    // Store links in variable
    linksArray.push(links[i]);

    // Works fine in console
    console.log(linksArray);
  }


  // Create text document — only saves 1st link in text doc
  var textDoc = document.createElement('a');

  textDoc.href = 'data:attachment/text,' + encodeURI(linksArray.join('\n'));
  textDoc.target = '_blank';
  textDoc.download = 'myFile.txt';
  textDoc.click();

  })();

https://jsfiddle/um4qhsks/1/

本文标签: javascriptSave List of Links from Array to Text File (almost got it working)Stack Overflow