JavaScript 如果提示密码为真,下载一个文件

JavaScript download a file if prompt password is true

如果用户输入正确的密码,我想下载一个文件

我的 html 文件中有一个按钮:

<button onclick="password()"><h3>Code</h3> </a>

在我的 .js 文件中,函数如下:

function password() {
    var password = prompt("Please enter the password");
    if (password === "password") {
        //download the file
    }
    else {
        alert("Password incorrect");
    }
}

要下载的文件位于“../file/file.txt”

我不确定用户输入正确文件后如何下载文件

试试这个。

<a id="download" style="display: none" 
    href="../file/file.text" 
    download>Download</a>


function password() {
    var password = prompt("Please enter the password");
    if (password === "password") {
        document.getElementById('download').click();
    }
    else {
        alert("Password incorrect");
    }
}