首页 > 解决方案 > 如何从输入中获取信息并将其放入href

问题描述

我是初学者,我有一个输入,在下面我有一个按钮,它是什么应用程序聊天的 href,我想知道如何获取输入中输入的文本并将其添加到 href,这里是代码如何:

<p>Send me a message right now Whats App</p>

  <input id="question" class="input border-red" type="text" placeholder="Write your question">      
  <a href="https://api.whatsapp.com/send?phone=9985985848&text=" class="button-red color-red css-section" target="_blank">Submit Doubt</a>

标签: html

解决方案


一些 Javascript 可以做到这一点(在纯 HTML 中不可能,除非你计算内联 JS):

var link = document.getElementsByTagName("a")[0];
function upd(element){
  var value = element.value;
  link.href="https://api.whatsapp.com/send?phone=9985985848&text="+value;
}
function showLink(element){//<--This function is optional. It is simply used to show that the code works
  console.log("href attribute value: "+element.href);
}
<p>Send me a message right now Whats App</p>

  <input id="question" class="input border-red" type="text" placeholder="Write your question" oninput="upd(this)">      
  <a href="" class="button-red color-red css-section" target="_blank" onclick="showLink(this)">Submit Doubt</a>

如果您希望href仅在单击时更改,而不是在用户在输入中输入内容时更新,您可以使用以下示例:

var input = document.getElementsByTagName("input")[0];
function showLink(element){
  element.href="https://api.whatsapp.com/send?phone=9985985848&text="+input.value;
}
<p>Send me a message right now Whats App</p>

  <input id="question" class="input border-red" type="text" placeholder="Write your question">      
  <a href="" class="button-red color-red css-section" target="_blank" onclick="showLink(this)">Submit Doubt</a>

一个jQuery方法:

$("#question").on("input",function(){$("a").attr("href","https://api.whatsapp.com/send?phone=9985985848&text="+$(this).val())}),$("a").on("click",function(){console.log("href attribute value: "+$(this).attr("href"))});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Send me a message right now Whats App</p>

<input id="question" class="input border-red" type="text" placeholder="Write your question">
<a href="" class="button-red color-red css-section" target="_blank">Submit Doubt</a>

用户输入时不更新链接的一种:

$("a").on('click',function(){$(this).attr('href','https://api.whatsapp.com/send?phone=9985985848&text='+$('input').val())})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Send me a message right now Whats App</p>

<input id="question" class="input border-red" type="text" placeholder="Write your question">
<a href="" class="button-red color-red css-section" target="_blank">Submit Doubt</a>


推荐阅读