gpt4 book ai didi

javascript - 根据输入值更改 href 目标

转载 作者:行者123 更新时间:2023-12-03 01:16:22 24 4
gpt4 key购买 nike

我目前正在创建一个允许自定义捐赠的捐赠表单。我的捐赠插件会检测 ?amount= url 值,并在用户登陆捐赠页面时预先选择它。

到目前为止,这是 html 输入:

<input type="text" placeholder="7.00" name="singular" id="singular">
<a href="http://example.com/donate/?amount=" id="myLink" class="et_pb_button dnt">Donate</a>

这是 JavaScript:

$('#singular').on('input', function() {
$('#myLink').prop('href', this.value);
});

但是,当我单击实际的捐赠按钮时,它会将输入的值添加到当前页面网址的末尾,例如:http://example.com/page1/7 而不是带您至http://example.com/donate/?amount=7

我知道这一定是非常简单的事情。我该如何解决这个问题?

错误时更新

加载https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js时建议的脚本工作正常。

但是当我删除该 jquery.min 并加载完整的 WordPress 核心 jquery(版本:1.12.4)时,Chrome Inspect 显示以下错误:

未捕获的类型错误:$不是函数

更新2.0

我找不到解决该错误的简单方法,但在我的搜索中,如果其他人有兴趣这样做,我确实找到了一个不依赖于 javascript 的解决方案:

How to pass input field values as a url query string that will be opened on click of a submit button?

最佳答案

您的代码的问题在于您正在用输入的值覆盖链接的 href 属性。这使得 anchor 的 href 相对于当前页面的 URL,这就是它导航到 URL 的原因,例如 http://example.com/page1/7

您需要使用输入框的值更改查询参数。

一种方法是使用 URL用于更改 amount 查询参数的 API。请参阅以下代码片段。

$('#singular').on('input', function() {
var href = new URL($('#myLink').prop('href'));
href.searchParams.set('amount', this.value);
$('#myLink').prop('href', href.toString())
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" placeholder="7.00" name="singular" id="singular">
<a href="http://example.com/donate/?amount=" id="myLink" class="et_pb_button dnt">Donate</a>

关于javascript - 根据输入值更改 href 目标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51998217/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com