首页 > 解决方案 > 将文本从文本框传递到 jsp 中的 href 调用的按钮

问题描述

我试图让用户单击一个按钮,然后该按钮在文本框中获取值并将其添加到 href 调用的末尾。我目前有一个将两个字符串加在一起并调用 href 的函数,但是当单击按钮时,似乎什么也没发生。这是我到目前为止得到的:

   <!DOCTYPE html>
<html>
  <head>
    <script>

function findAccountID() {
  var text = document.getElementById('textInput');
  var value = encodeURIComponent(text.value); //encode special characters
  location.href = '**href path here**'+value; //goto URL
}

</script>
  </head>
  <body>
    <div>
      <input type="text" id="textInput" />
      <input type="button" value="Find Account ID" onclick="findAccountID();" />
    </div>
  </body>
</html>

标签: javascripthtmlhref

解决方案


您可能需要/在 location.href 和 value 之间添加斜杠 在以下代码段中,newHref变量是 location.href& 文本框值的串联。如果您打算导航到设置location.href为此的新网址newHref

function findAccountID() {
  var text = document.getElementById('textInput');
  var value = encodeURIComponent(text.value); //encode special characters
  let newHref = location.href + '/' + value
  console.log(newHref)
}
<div>
  <input type="text" id="textInput" />
  <input type="button" value="Find Account ID" onclick="findAccountID();" />
</div>


推荐阅读