2011-08-15 105 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可以做同樣的事情完全一樣。

相關問題