<html>
<title>My Web Page</title>
<form onsubmit="return redirect()">
<input id="search_form_input" type="text" name="query" />
<input type="submit" value="Search" />
</form>
<script type="text/javascript">
function redirect() {
var link = document.getElementById('link');
link.href += document.getElementById('search_form_input')
return false;
}
</script>
<body>
<p>
<a id="link" href="http://www.cnn.com/">CNN</a>
</p>
</body>
</html>
基本上 id 就像来自表单的输入一样,将其自身扩展到 CNN.com 的 URL 上。例如,在表单中输入政治并提交,然后单击 CNN 链接会将其带到 CNN.com/politics。我这样做的方式正确吗?
最佳答案
您正在做的事情以及您做事的方式很疯狂。寻求其他解决方案,但您的问题很简单。您将整个元素附加到 href
字符串。所以不是
link.href += document.getElementById('search_form_input')
使用
link.href += document.getElementById('search_form_input').value
完整的结果是:
<html>
<title>My Web Page</title>
<form onsubmit="return redirect()">
<input id="search_form_input" type="text" name="query" />
<input type="submit" value="Search" />
</form>
<script type="text/javascript">
function redirect() {
var link = document.getElementById('link');
link.href += document.getElementById('search_form_input').value
return false;
}
</script>
<body>
<p>
<a id="link" href="http://www.cnn.com/">CNN</a>
</p>
</body>
</html>
至少尝试一下 jQuery。
关于javascript - 以下代码有什么问题吗? (html/javascript/href),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13435972/