如何在Vanilla JS中将URL参数与输入字段绑定?

问题描述

我有一个运行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小提琴上方或JS小提琴上运行代码段似乎不适用于URL参数。

如果输入内容发生更改,我也要使用新值更新URL 。如何在香草JS中实现?

解决方法

您可以添加一个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')
    );
});