为什么我的文件 blob 保存的是整个网页而不是输入的字符串?

Why is my file blob saving the whole webpage rather than the inputted string?

我有这个函数接受一个字符串,我希望人们能够下载一个包含该字符串的文本文件。但是,每当我单击 link 时,下载的文件只包含整个 HTML 页面而不是字符串。

JS:

function downloadFile(names) {
  var text = names.toString();
  $('#downloadlink').href = createFile(text);
}

function createFile(text) {
  var data = new Blob([text], {type: 'text/plain'});

  if (textFile !== null) {
    window.URL.revokeObjectURL(textFile);
  }

  var textFile = window.URL.createObjectURL(data);

  return textFile;
}

HTML:

<a download="colors.txt" href="" id="downloadlink">Download</a>

为什么要这样做?我是否错误地构建了 Blob?我该如何解决?

在运行时 href 属性为空。 添加一个 $(document).ready 函数或使用经典方式:

window.addEventListener("load", function()
{
    document.getElementById('downloadlink').href = window.URL.createObjectURL(new Blob(["content"], {type: 'text/plain'}));
});

这里的问题是,当您使用 $('#downloadlink') 时,jQuery 魔法掩盖了您实际在做什么。 jQuery 将 $ 中的 returns 包装在一个 jQuery 对象中,该对象是一个类似数组的结构。因此,即使 id 选择器(可能)returns 一个元素,jQuery 仍然会为您提供一个数组。

因此,您不能$('#stuff').href。您需要像这样使用 jQuery 的 attr()

$('downloadLink').attr('href', createFile(text));

与大多数 jQuery 函数一样,它对 $ 返回的数组中的所有元素应用一些操作。

工作JSBin