JavaScript <a> href 替换无效

JavaScript <a> href replacing is not working

我正在做一个字体下载资源网站,这是我的 JS 和我的一些 html:

var element, text, font, download, value;

function tick() {
  element = document.getElementById("text");
  font = document.getElementById("fontfamily");
  text = document.getElementById("dummy-text");
  download = document.getElementById("downlink");
  text.innerHTML = element.value;
  text.style.fontFamily = font.value;
  value = font.value + ".tff";
  download.setAttribute("href", value);
}
<input type="text" id="text" value="Lorem ipsum dolor set amit.">
<select id="fontfamily">
  <optgroup label="Apple">
    <option>Helvetica Neue</option>
  </optgroup>
  <optgroup label="Google">
    <option>Roboto Regular</option>
    <option>Roboto Light</option>
    <option>Roboto Bold</option>
    <option>Roboto Italic</option>
  </optgroup>
  <optgroup label="Monotype">
    <option>Century Gothic</option>
  </optgroup>
  <optgroup label="Nintendo">
    <option>Wii Sans Regular</option>
    <option value="SMW">Super Mario World Sans</option>
  </optgroup>
</select><button onclick="tick()">Set Text</button>
<br><br>
<h1 id="dummy-text" style="font-family: Helvetica Neue;">Lorem ipsum dolor set amit.</h1><a href="Helvetica Neue.ttf" id="downlink"><button style="margin: 0;">Download</button></a>

但是当我点击“下载”时,我去的link是[object%20HTMLSelectElement].tff,显然不存在

有什么帮助吗?

您目前遇到的问题是您设置的是属性,而不是 href。设置你的 href

let download = document.getElementById("downlink");
download.href = "https://example.com";

这应该可以解决问题![​​=11=]

注意:我注意到你是新会员!首先,欢迎来到 Whosebug。其次,请务必通过单击帮助您解决问题的答案旁边的复选标记来标记您的问题的答案,这样人们就知道这个问题得到了答案,新人也可以轻松找到它!

在 运行 代码片段之后,我看到即使将正确的值设置为 href,当您单击 Download 按钮时它也会得到 URL encoded .

这就是 Roboto Regular 将变成 Roboto%20Regular 的方式。

download 属性添加到 <a> 标记以指定当用户单击超链接时将下载目标。

var element, text, font, download, value;

function tick() {
  element = document.getElementById("text");
  font = document.getElementById("fontfamily");
  text = document.getElementById("dummy-text");
  download = document.getElementById("downlink");
  text.innerHTML = element.value;
  text.style.fontFamily = font.value;
  value = font.value + ".tff";
  download.href = value;

}
<input type="text" id="text" value="Lorem ipsum dolor set amit.">
<select id="fontfamily">
  <optgroup label="Apple">
    <option>Helvetica Neue</option>
  </optgroup>
  <optgroup label="Google">
    <option>Roboto Regular</option>
    <option>Roboto Light</option>
    <option>Roboto Bold</option>
    <option>Roboto Italic</option>
  </optgroup>
  <optgroup label="Monotype">
    <option>Century Gothic</option>
  </optgroup>
  <optgroup label="Nintendo">
    <option>Wii Sans Regular</option>
    <option value="SMW">Super Mario World Sans</option>
  </optgroup>
</select><button onclick="tick()">Set Text</button>
<br><br>
<h1 id="dummy-text" style="font-family: Helvetica Neue;">Lorem ipsum dolor set amit.</h1><a href="Helvetica Neue.ttf" id="downlink"><button style="margin: 0;" download>Download</button></a>