【问题标题】:How to create a link that concatenates the user input in HTML如何在 HTML 中创建连接用户输入的链接
【发布时间】:2021-04-28 17:17:46
【问题描述】:

<!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>

How to create a link incorporating user input from the input box

我正在尝试一种类似的机制,但由于我对 HTML 太陌生,我无法快速使用 jquery。

感谢任何帮助!谢谢!

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

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

【问题讨论】:

  • 感谢您的快速回复。不胜感激,如果你能简单介绍一下
  • 请在此处发布您的代码,而不是在外部站点。
  • post_id 应该是post_id.value
  • 'code'

标签: html jquery url concatenation customization


【解决方案1】:

您需要将 jQuery 代码放在加载 jQuery 库的代码之后的 &lt;script&gt; 标记内。

还将代码放在$(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>

【讨论】:

  • 感谢您修改。从当前代码中,它重定向到堆栈溢出,而我知道我需要更改行中的 href --> $("a#link") 有没有一种方法可以让我为不同的 URL 多次调用用户输入?链接代码主体 - 我试图将其作为 google.com 的输入
  • 这听起来像是您要求上一堂关于编写 JavaScript 和 jQuery 代码的完整课程。您需要阅读教程。
【解决方案2】:

您只需要拥有&lt;script&gt; 标记和jQuery 文档就绪标记$(function() { 即可使其工作。

<script>
$(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>

【讨论】:

    猜你喜欢
    • 2014-01-26
    • 2018-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 2013-03-07
    相关资源
    最近更新 更多