【问题标题】:Anything wrong with the following code? (html/javascript/href)下面的代码有什么问题吗? (html/javascript/href)
【发布时间】:2012-11-06 07:44:25
【问题描述】:
<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。我这样做的方式是否正确?

【问题讨论】:

  • 为什么你的表格在标题中?它必须在体内!
  • 它不在标题中。但它也不在正文中 :) 总的来说,它的标记很糟糕。
  • 你的 也不在 字段中...这是一些看起来很恶心的 html。

标签: javascript html forms hyperlink href


【解决方案1】:

你在做什么以及你是如何做的都很疯狂。寻求其他解决方案,但您的问题很简单。您将整个元素附加到 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。

【讨论】:

  • 没有“;”在 .value 之后,标记仍然非常糟糕。关闭,将
  • 我也会走 jQuery 路线,但这不是绝对必要的。我要做的主要更改是删除表单提交。我没有发布单独的答案,因为这个答案涵盖了这个问题。
  • 感谢您的帮助。我现在看到我做错了什么,想扇自己耳光。我会对 jquery 方法感兴趣。如果有人可以为我提供一个链接,我可能会参考这将有所帮助。还有一件事,是否可以保存搜索输入值并保持不变。例如,使用当前代码在链接之间来回浏览会重置表单字段。如果你运行代码,你会看到我在说什么。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-27
  • 1970-01-01
  • 2017-01-21
相关资源
最近更新 更多