html - 如何在 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 ] 类似这样的东西,而不是用户输入字符串。
解决方案
您需要将 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>
推荐阅读
- php - 如果有人将 / 添加到 url,则重定向
- reactjs - 来自状态的 React Ant Design defaultValue 不起作用
- html - 移动版页面不向下滚动
- arrays - 在scala中重复函数n次
- api - Confluence REST API 不会使用新编辑器创建页面
- javascript - 如何避免点击带ID的锚点时跳到顶部
- c# - 如何在 C# 中计算没有 WMI 和性能计数器的 CPU 使用率?
- javascript - 为什么在这段代码的 $('selector').delegate() 方法中不能调用 $.ajax() 方法
- angular - 导航到新路线不会在 Angular 中加载组件数据
- bash - 通过管道计算整数频率