<form class="form-search" id="q-form" method="get">
<div class="input-append" id="q-input">
<input type="text" class="span6 search-query" name="q" title="輸入任意關鍵詞皆可搜索"
value="" onkeypress="return handleKeyPress(event)">
<button type="button" class="btn" onclick="submitForm()">搜索</button>
</div>
</form>
<script>
function handleKeyPress(event) {
if (event.keyCode === 13) { // 13是回車鍵的鍵碼
event.preventDefault(); // 阻止默認行爲
submitForm(); // 調用submitForm()方法處理表單提交
}
}
function submitForm() {
// 獲取輸入框的值
var query = document.getElementById("q-input").querySelector("input[name='q']").value;
// 組合URL
var url = "/moreSearch/" + encodeURIComponent(query) + ".html";
// 重定向到URL
window.location.href = url;
}
</script>
將提交按鈕的type屬性設置爲button,這樣它就不會提交表單。然後使用JavaScript來獲取輸入框的值,並將它們組合成一個URL。最後,使用JavaScript中的window.location.href將頁面重定向到新的URL。
如果用戶在輸入框中按下回車鍵,它會默認觸發表單的提交行爲,爲了避免這種情況,可以使用JavaScript來截取回車事件,並阻止默認行爲。
帝國cms 點擊提交表單後,用js組合url並重定向
很多時候,搜索的鏈接太長,帶着很多參數,我們想要進行僞靜態修改,同時也希望鏈接能二次訪問。
原來的html代碼:
我們修改爲: