我有这个代码:
function src(){
var id = document.getElementsByName("query")[0].value;
window.location.href = "/search/?query=" + id;
}
var f_src = document.getElementById("search_form");
if(f_src)
f_src.onsubmit = function(){src();return false;};
我在提交部分遇到问题:当我在“url”字段中输入“example”时,我希望重定向到”/search/?query=example",但它不起作用,有什么帮助吗?
HTML:
<form id="search_form" method="get" action="" name="search_f">
<input id="search_field" maxlength="100" name="query" type="text" value="" placeholder="<?php echo $src_txt; ?>">
<input id="search_button" type="submit" value="">
</form>
谢谢。
最佳答案
除了您可能遇到的问题之外,您无需 JavaScript 也可以实现相同的行为。您只需将表单元素命名为“query”,并使其向 /search
提交 GET 请求即可:
<form id="search_form" method="get" action="/search/" name="search_f">
<input id="search_field" maxlength="100" name="query" type="text" value="" placeholder="<?php echo $src_txt; ?>">
<input id="search_button" type="submit" value="">
</form>
action
属性告诉浏览器向何处发出请求。每个具有 name
的表单控件元素都将包含在查询字符串中及其值。
无需 JavaScript。
关于javascript - 表单 onsubmit 执行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20551272/