我有一个输入文本框和一个搜索提交按钮,当用户点击搜索提交按钮时,我想将用户重定向到网址http://testsearch/results.aspx?k=<value of text box k>,例如,如果用户将"StackOverflow"放入文本框然后单击搜索按钮,我想要将用户重定向到以下页面,
HTTP://testsearch/results.aspx K = StackOverflow的
我发现当我使用按钮搜索按钮时,它可以工作(参见下面的源代码),
<input type="text" id="k" name="k" />
<input type="button" id="Go" value="Search" onclick="location.href = 'http://somemachine/Search/results.aspx?k='+document.getElementById('k').value;"/>
Run Code Online (Sandbox Code Playgroud)
但是当我使用提交搜索按钮时,它不起作用(见下面的源代码),为什么?
<input type="text" id="k" name="k" />
<input type="submit" id="Go" value="Search" onclick="location.href = 'http://somemachine/Search/results.aspx?k='+document.getElementById('k').value;"/>
Run Code Online (Sandbox Code Playgroud)
乔治,提前谢谢
Sar*_*raz 11
你甚至可以这样使用提交按钮:
<input type="submit" id="Go" value="Search" onclick="document.location='http://testsearch/results.aspx?k=StackOverflow'; return false;" />
Run Code Online (Sandbox Code Playgroud)
语义提交按钮用于提交表单而非重定向页面.您应该使用普通按钮类型.然而,正如我所示,你也可以使用提交按钮,但我认为这不是语义.
以下行阻止提交表单.
return false;
Run Code Online (Sandbox Code Playgroud)
这就是你在代码中遗漏的:)
谢谢
<button>-elements并且<input type="button"/>默认情况下不做任何事情,除非你告诉他们用Javascript做某事.
<input type="submit"/> 将提交其所在的表格.
所以,如果<input type="submit"/>不行,你可能不会在<form/>-element自己身上.