根据输入值更改 href 目标



我目前正在创建一个允许自定义捐赠的捐赠表格。我的捐赠插件检测到 ?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);
});

但是,当我单击实际捐赠按钮时,它会将输入的值添加到当前页面 url 的末尾,例如: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的解决方案:

如何将输入字段值作为 url 查询字符串传递,单击提交按钮即可打开该字符串?

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

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

执行此操作的一种方法是使用URLAPI 更改amount查询参数。请参阅以下代码片段。

$('#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>

最新更新