1 GP
網頁按enter觸發submit事件
作者:怪鳥│2011-11-15 18:22:49│巴幣:2│人氣:2527
在網頁上,有時候我們會讓特定的<intpu type="text"/>在按下enter後觸發submit事件,但是如果form的action target和原本的不同時,直覺上會寫成
function Search(){
if(e.keyCode==13){
document.location.href ="newForm.htm?val=xxx";
}
}
<intpu type="text" onkeypress="Search()"/>
但是,今天測試發現,事情不是我想的那樣。經過測試,瀏覽器會聰明的替<intpu type="text"/>加上onkeypress後submit的動做。所以不管我如何設定location.href,當javascript執行到location.href時都會先觸發submi動做,取代location.href原本要做的事,造成回到原本action target指向的網頁,無法轉址到newForm.htm。也就是所謂的race condition。
解決辦法就是function要回傳false來停止submit事件。改寫成以下範例
function Search(e){
e = e || window.event;
var keynum = e.keyCode || e.which;
if(keynum === 13){
document.location.href ="newForm.htm?val=xxx";
return false;
}
}
<intpu type="text" onkeypress="return Search(event)"/>
引用網址:https://home.gamer.com.tw/TrackBack.php?sn=1464676
All rights reserved. 版權所有,保留一切權利