0
我有以下的HTML代码,用功能来下载内容为纯文本:JS - 的“数据原标题”值传递给javascript函数
<div class="col-sm-7">
<ul class="nav nav-pills nav-justified">
<li role="presentation" class="active">
<a id="fileNameId" data-toggle="pill" href="#tab" style="font-weight:bold">Server Name
<button class="btn glyphicon glyphicon-download-alt text-primary tips pull-right" type="button" onclick="downloadFile('fileNameId', 'contentId')" data-placement="bottom" data-original-title="Download1" style="display:block"> </button>
</a>
</li>
</ul>
<div class="tab-content">
<div id="tab" class="tab-pane fade in active">
<pre id="contentId">Some text to download</pre>
</div>
</div>
<script>
function downloadFile(fileNameId, contentId) {
var element = document.createElement('a');
var content = document.getElementById(contentId).innerText.replace(/\r?\n/g, "\r\n");
var fileName = document.getElementById(fileNameId).innerText.trim();
console.log(document.getElementById(fileNameId).innerText);
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(content));
element.setAttribute('download', fileName+'.txt');
element.style.display = 'none';
document.body.appendChild(element);
element.click();
console.log(element);
document.body.removeChild(element);
}
</script>
注意:
contentId
是一个pre
元素,其文本需要下载,fileNameId
的innerText动态更改,以便下载的文件名也会相应地改变。现在
,问题是,在JS的fileName
变量包含额外的文本 - “下载1”,这恰好是按钮的data-original-title
属性的值。这可以看出,在执行console.log的O/P:
Server Name Download1
正因为如此,下载的文件名变为 - Server Name -Download1.txt
这是一个预期的行为?如果data-original-title
的值最终从JS传递过来,那么我所做的全部是document.getElementById(fileNameId).innerText
?
之前,你可以共享标记,以便我们能够看到的内容ID和filenameid之间的关系? – gurvinder372
你的代码缺少一些东西。我做了一个[Fiddle](https://jsfiddle.net/jko48x3u/)和'document.getElementById(fileNameId).innerText'按预期返回“Server Name”。你在使用某种数据绑定框架吗? –
@ gurvinder372我编辑了问题 – ss2025