微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何在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')
    );
});

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。