先看代碼,
<form id="searchMyselfForm" method="post" action="/Home/SearchMySelf" onsubmit="return false">
<input id="searchMyself" class="form-control form-control-dark w-100" type="text"
onkeydown="SubmitSearch(event)" placeholder="查找已有倉庫中的物品" aria-label="Search" />
</form>
function SubmitSearch(event) {
var e = event || window.event || arguments.callee.caller.arguments[0];
//if (e && e.keyCode == 27) { // 按 Esc
// //要做的事情
//}
//if (e && e.keyCode == 113) { // 按 F2
// //要做的事情
//}
if (e && e.keyCode == 13) { // enter 鍵
//alert("此處回車觸發搜索事件");
var isSubmitForm = true;
var searchMyselfObj = document.getElementById("searchMyselfForm");
var searchStr = $("#searchMyself").val();
searchStr = searchStr.replace(/(^\s*)|(\s*$)/g, '');//去除空格;
if (searchStr == "" || searchStr == null || searchStr == undefined) {
isSubmitForm = false;
} else {
isSubmitForm = true;
}
if (isSubmitForm) {
searchMyselfObj.submit();
} else {
return;
}
}
}
問題: 即使input輸入框爲空,也會觸發submit到後臺(也就是驗證爲空沒用,),剛開始以爲是驗證的問題,後來經過多次度度度娘,找到一篇文章
https://blog.csdn.net/weixin_33698823/article/details/91680398
其中提到了這樣一句話:
"如果table在form表單中,那麼必須要加一個屬性:οnsubmit=return false; "
所以在form屬性中加上οnsubmit=return false;就解決問題了。