2011-08-15 66 views
1
<form method="get" action="/" onsubmit="SubmitForm()"> 
<input type="text" title="" value="" name="q" class="search-input" id="gsearch" /> 
<input type="submit" value="" name="sa" id="search-button"/> 
</form> 
<script type="text/javascript"> 
function SubmitForm(){ 
window.open("http://test.com/gsearch.php?cx=015214977:8tebxhu0mrk&cof=FORID:11&ie=GB2312&as_q="+document.getElementById('gsearch').value); 
return false; 
} 

</script> 

当我提交按钮时,原始页面刷新一次。如何预防它?谢谢。为什么页面刷新一次?

回答

3

改变你的形式onsubmit属性,并插入一个这样的:

<form method="get" action="/" onsubmit="return SubmitForm();"> 
+0

没关系。谢谢。为什么添加回报。有用?谢谢。 – zhuanzhou

+1

onsubmit属性是一个JavaScript脚本。如果该脚本返回false,则不会提交表单。首先,你的脚本是_SubmitForm()_,它只是调用函数,并且没有_return false_。但在插入返回后,现在在onsubmit脚本中,返回SubmitForm的返回值,该值为false。 – Saeed

3

你正确地从你的SubmitForm方法返回false,但你没有捕捉在onsubmit处理该窗体的响应。将其更改为:

<form method="get" action="/" onsubmit="return SubmitForm()"> 

请注意在上面添加了return关键字。

+0

谢谢。为什么添加回报。有用? – zhuanzhou

+0

@zhuanzhou - 出于我在回答中指定的确切原因。但是,当你接受* far * less信息的答案时,我不会费心尝试再次解释它 – Jamiec

1

您无需为此使用JavaScript。这将工作同样的方式:

<form method="get" target="_blank" action="http://test.com/gsearch.php"> 
    <input type="hidden" name="cx" value="015214977:8tebxhu0mrk" /> 
    <input type="hidden" name="cof" value="FORID:11" /> 
    <input type="hidden" name="ie" value="GB2312" /> 
    <input type="text" title="" value="" name="as_q" class="search-input" id="gsearch" /> 
    <input type="submit" value="Submit" id="search-button"/> 
</form> 

JavaScript是所有好和好,但实在没有必要使用它时,纯HTML可以做同样的事情完全一样。

相关问题