【发布时间】:2021-05-16 09:58:06
【问题描述】:
This post (Arindam Roychowdhury) 展示了如何使用文本框值来更改锚标记的 href。
<html>
<body>
Hi everyone
<p id="result"></p>
<textarea cols="40" id="SearchText" rows="2"></textarea>
<button onclick="myFunction()" type="button">Submit!</button>
<script>
function myFunction() {
var result = document.getElementById("SearchText").value;
document.getElementById("result").innerHTML = result;
document.getElementById("abc").href="http://arindam31.pythonanywhere.com/hello/" + result;
}
</script>
<a href="#" id="abc">abc</a>
太棒了!但是为了导航到新的 url,您需要单击锚标记。 两次点击完成这项工作。
是否可以单击锚点并运行更改 href 然后导航到新 url 的 JS 代码?只需单击 即可访问新网址。谢谢。
这是实现window.location代码phuzi提出的修改代码...
<p id="result"></p>
<textarea cols="40" id="SearchText" rows="2"></textarea>
<button onclick="myFunction()" type="button">Submit!</button>
<script>
function myFunction() {
var result = document.getElementById("SearchText").value;
document.getElementById("result").innerHTML = result;
window.location= "http://example.com/live/" + result;
}
</script>
另一个想法:
This post 展示了使用 on.input 来监视文本框的每次更改。如果包含更新锚标记的href的代码,并且当用户移动到具有更新href的链接时,单击它将传递所有字段中的当前值。
<style>
p.hidden {
display: none;
}
</style>
<p id="result" class="hidden"> </p>
<textarea cols="40" id="SearchText" rows="1"></textarea>
<script>
jQuery('#SearchText').on('input', function() {
//alert('Text1 changed!');
var result = document.getElementById("SearchText").value;
document.getElementById("result").innerHTML = result;
document.getElementById("abc").href="http://example.com/live/" +
result;
});
</script>
<a href="#" class="colorbox-popup" id="abc">Add New Record</a>
与简单的重定向相比,使用 href 的优势在于允许附加类 - 在这种情况下,可以在弹出窗口中打开新链接。
再次感谢大家对此提供的帮助。
【问题讨论】:
-
Window.location = 'Your new url'不需要更新锚标签上的href -
这能回答你的问题吗? How do I redirect with JavaScript?
-
试试这个。 jsfiddle.net/pbu1f3Ly 只是应用了@phuzi 的建议。
-
谢谢 phuzi。正如您所说,无需更新锚标记。好的是这可以在 Drupal 页面中工作而不会出现任何错误。问题解决了。
标签: javascript html href