为了账号安全,请及时绑定邮箱和手机立即绑定

如何创建一个提交按钮,在 URL 上附加一个值并在提交后转到该 URL?

如何创建一个提交按钮,在 URL 上附加一个值并在提交后转到该 URL?

月关宝盒 2023-09-21 16:21:18
因此,基本上,要求是用户在文本字段中输入一个值,然后单击“提交”后,他将被重定向到具有基于其输入值的 URL 的页面,例如:用户输入:测试点击提交后就变成了一个URL: http: //test.example.com然后重定向到该 URL我一直在尝试使用以下代码:<script>    function resetId(){  var idInput = document.getElementById("id");  var suffix=".example.com";            alert("Value before submit:" + idInput.value);}</script><form action="#" method="post" onsubmit="resetId();return false" >    <input type="text" name="id" value="domain" id="id"><br>    <input type="submit"></form>我能够将其附加为后缀,但随后我也感到困惑,因为这是 URL,我需要整个内容,所以我认为有更好的方法来实现这一点,而不是做我已经做的事情。抱歉,我是编码新手,并且仍在学习新概念。
查看完整描述

2 回答

?
猛跑小猪

TA贡献1858条经验 获得超8个赞

有很多方法可以实现它。

利用模板字符串和提示的单行方法(创建一个弹出窗口,提示用户输入某些内容)。

window.location.replace(`http://${prompt('Input:')}.example.com`)

使用形式及其onsubmit属性(您的方法)。请注意,对于 ES6,请使用let或const而不是var

function resetId(){

    const idInput = document.getElementById("id");

    const url = `http://${idInput.value}.example.com`;

    alert("Value before submit: " + url);

    window.location.replace(url);

}

<form action="#" method="post" onsubmit="resetId();" >

    <input type="text" name="id" value="domain" id="id">

    <input type="submit">

</form>

一种不使用表单而是使用按钮的方法。

// Same as above

function resetId(){

    const idInput = document.getElementById("id");

    const url = `http://${idInput.value}.example.com`;

    alert("Value before submit: " + url);

    window.location.replace(url);

}

<div>

    <label for="id">Input:</label>

    <input type="text" name="id" value="domain" id="id">

</div>

<button onclick="resetId()">submit</button>

注意:不要<br />在表单中使用新行,而是考虑对每行使用<label>并<input>包裹在<div>如下所示的内容中:


<div>

    <label for="something">Something:</label>

    <input type="text" name="something" id="something" />

</div>


查看完整回答
反对 回复 2023-09-21
?
MM们

TA贡献1886条经验 获得超2个赞

只需替换这行代码

<form action="#" method="GET" onsubmit="resetId();return false" >


查看完整回答
反对 回复 2023-09-21
  • 2 回答
  • 0 关注
  • 63 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信