如何在HTML中将文本输入值添加到URL的末尾

How to add the text input value to the end of the URL in HTML?

本文关键字:添加 URL 输入 HTML 文本      更新时间:2023-09-26

我是HTML新手;我需要将文本输入中的数字附加到url的末尾。我该怎么做?

<input type='"number'" id='"b'" name='"b'" value='"1'">'
<script>
  var str,i;
  i= parseInt(b.value);
  str+="<a href=/t"+i+">Send</a>";
</script>

当我尝试使用上面的示例代码时,当单击send时,它总是发送b的初始值"1"。尽管我更改了b的值并尝试发送它,但它发送的是相同的初始值。

有人能帮我吗?

试试这个

<input type="number" id="b" name="b" value="1">
<a id="c" href="">Send</a>
<script>
  document.getElementById("c").addEventListener("click", function() {
    var i = document.getElementById("b").value;
    this.setAttribute("href", "/t" + i);
  });
</script>

代码的问题在于它在页面加载时写入"数字"框的初始值。你想要的快速版本是:

<input type="number" id="b" name="b" value="1" onchange="link1.href='t/'+parseInt(b.value);">
<a id="link1" href="">Send</a>

此代码适用于最新版本的Chrome、Firefox和Internet Explorer。您可能希望使用jQuery或document.getElementById来进行页面元素引用。

您可以使用id 搜索元素

var el = document.getElementById("b")

使用.value 访问其值

var val =el.value

并使用window.location 将其设置为url

var url = window.location.href; // this will return current url
url += "?key=" + val;
window.location.href=url;

并没有得到更新值的另一个原因是在页面加载时调用脚本。您必须在事件中更新它。查找blur事件,或者您可以有一个按钮和点击事件,计算url并路由到它。