首页 > 解决方案 > 如何在 HTML 中创建连接用户输入的链接

问题描述

<!DOCTYPE html>
<html>
<head>

<!-- $("input#post_id").on("change", function(){ // Whenever this field changes

  var post_id = $("input#post_id").val(); // Get the value of the field

  $("a#link").attr("href", "https://stackoverflow.com/questions/" + post_id); // Update the href in the link to match the id inserted in the input field

}); -->



<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<label>Enter the DP ID below </label>

<br>

<input id="post_id" type="text">

<a id="link" href='https://www.google.com/search?'+post_id.value>Click to redirect</a>

</body>
</html>

如何创建包含来自输​​入框的用户输入的链接

我正在尝试一种类似的机制,但由于我对 HTML 太陌生,我无法快速将它与 jquery 结合起来。

感谢任何帮助!谢谢!

我的示例查询 - https://www.w3schools.com/code/tryit.asp?filename=GPZYOB9C4JFW

当我最初尝试这种方法时,生成的 url 有 [ input object HTML ] 类似这样的东西,而不是用户输入字符串。

标签: htmljqueryurlconcatenationcustomization

解决方案


您需要将 jQuery 代码放在<script>加载 jQuery 库的代码之后的标签内。

还将代码放入其中,$(document).ready()以便在 HTML 完全加载后运行。

<!DOCTYPE html>
<html>

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script>
  $(document).ready(function() {
    $("input#post_id").on("change", function() { // Whenever this field changes
      var post_id = $("input#post_id").val(); // Get the value of the field

      $("a#link").attr("href", "https://stackoverflow.com/questions/" + post_id); // Update the href in the link to match the id inserted in the input field

    });
  });  
</script>
</head>

<body>
  <label>Enter the DP ID below </label>
  <br>
  <input id="post_id" type="text">
  <a id="link" href='https://www.google.com/search?'>Click to redirect</a>
</body>

</html>


推荐阅读