我正在制作一个工具,其中包含一些我可以在其中输入信息的字段。我的表单中有两个按钮,一个只是清除字段,第二个我想开始下载字段中的数据。按钮代码为
<button id="button-reset">Clear</button>
<button id="button-save">download</button>
其中按钮属性是在 .form_box 按钮的早期样式定义中定义的{}。作为 javascript 的新手,我复制了以下代码以促进下载功能
<script language="Javascript" >
function download(filename, text) {
var pom = document.createElement('a');
pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
pom.setAttribute('download', filename);
pom.style.display = 'none';
document.body.appendChild(pom);
pom.click();
document.body.removeChild(pom);
}
</script>
在我的表单标签中,我调用下载函数并传递参数,我需要命名要下载的 .txt 文件以及要放入文件中的文本。这工作正常但是,当按下表单中的任何按钮时调用下载功能。我需要隔离对“下载”按钮的函数调用。我的想法是我需要将 pom.click() 语句包装在一个 if 中,其中“if is true”是在按下下载按钮时。但我可能完全错了。 我尝试过的一件事是从表单标签中删除 download() 调用并将其放入按钮标签中,如下所示:
<button type="button" onclick="download(this['ticket'].value, this['followup'].value); return false" id ="button-save">download</button>
这确实阻止了“清除”按钮调用 download() 函数,但是“下载”按钮现在什么都不做。 非常感谢您的帮助。
最佳答案
this
是对表单的引用,但现在它是对按钮的引用。
指定表单而不是 this
就可以了。例如:
<button type="button" onclick="download(document.forms[String form_name]['ticket'].value, document.forms[String form_name]['followup'].value); return false" id ="button-save">download</button>
关于javascript - 为表单中的 download() 函数调用隔离特定按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52803254/