【问题标题】:How to bind a URL parameter with an input field in Vanilla JS?如何将 URL 参数与 Vanilla JS 中的输入字段绑定?
【发布时间】:2021-01-25 20:47:58
【问题描述】:

我有一个运行here 的示例,其中输入由?amount=123 设置

const query = new URL(location).searchParams
const amount = parseFloat(query.get('amount'))

console.log("amount", amount)
document.getElementById('amount').value = amount
<label>
  Amount
  <input id="amount" type="number" name="amount">
</label>

抱歉,运行上面或 JS fiddle 上的代码 sn-p 似乎不适用于 URL 参数。

如果输入发生更改,我希望 URL 也更新,使用新值。我如何在 vanilla JS 中实现这一点?

【问题讨论】:

  • 你可以简单地使用history API来改变URL
  • 您是否也需要它来重新加载页面,或者只是将其添加到 URL 地址和历史记录中,或者只是更改 URL 地址而不将其添加到历史记录?
  • 这是你的 jsfiddle 吗? jsfiddle.net/kaihendry/e67ywq8f/?amount=231

标签: javascript html url-parameters


【解决方案1】:

您可以添加一个input 事件侦听器并使用window.history.replaceState

const origin = window.location.origin;
const path = window.location.pathname;

input.addEventListener('input', () => {
    // Set the new 'amount' value
    query.set('amount', input.value);
    // Replace the history entry
    window.history.replaceState(
        null,
        '',
        origin + path + '?amount=' + query.get('amount')
    );
});

【讨论】:

  • 通过连接这样的字符串来构建 url:origin + path + '?amount=' + query.get('amount') ... 这是最佳实践吗?
  • 它只改变amount 查询并维护原始URL,所以,我会这么说。
  • 对未经测试的浏览器使用完整(绝对)URL 可能是合理的预防措施,但从我尝试使用(相对)'?search' 片段的方法来看,效果相同。 (查看规格我认为它应该以这种方式工作,因为 base 应该是 window.location 的暗示,但我不确定我是否理解正确;html.spec.whatwg.org/multipage/…
猜你喜欢
  • 2020-11-01
  • 2018-04-03
  • 1970-01-01
  • 1970-01-01
  • 2020-05-15
  • 1970-01-01
  • 2023-03-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多