这显然是一个简化的测试,但如果这有效,我可以做我的。
我想创建一个包含字符串code
的文件并下载txt文件。
txt文件应该有bla bla bla
$("button[id^='downloadTestCase-']").click(function() {
var code = "bla bla bla"
var file = new Blob([code], {
type: 'text/plain'
});
window.open(URL.createObjectURL(file));
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="btn btn-rounded btn-danger-outline" id="downloadTestCase-Teste50" name="Teste50">Download</button>
&#13;
答案 0 :(得分:1)
您需要两个单独的代码块,因为IE使用msSaveBlob:
document.getElementById('downloadTestCase-Teste50')
.addEventListener('click', function () {
var blob = new Blob(
['bla bla bla'],
{ type: 'text/plain' }
);
var filename = 'result.txt';
if (window.navigator
&& typeof window.navigator.msSaveOrOpenBlob === 'function') {
window.navigator.msSaveOrOpenBlob(blob, filename);
}
else {
var objectURL = URL.createObjectURL(blob);
var a = document.createElement('a');
a.href = objectURL;
a.download = filename;
document.body.appendChild(a);
a.click();
URL.revokeObjectURL(objectURL);
}
}, false);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="btn btn-rounded btn-danger-outline" id="downloadTestCase-Teste50" name="Teste50">Download</button>
答案 1 :(得分:0)
<a>
代码。<a>
标记。
$("button[id^='downloadTestCase-']").click(function() {
var data = "bla bla bla"
var fileName = "code"
saveData(data, fileName);
});
var saveData = (function () {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
return function (data, fileName) {
var blob = new Blob([data], {type: "text/plain"}),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
};
}());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="btn btn-rounded btn-danger-outline" id="downloadTestCase-Teste50" name="Teste50">Download</button>
这是基于Stack here
的回答