症狀:
當一個form表單內只有一個文本輸入框時,當我們按下回車鍵會自動刷新頁面內容,現象代碼如下:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>測試</title> </head> <body> <form> <label for="title">ToDoList</label> <input type="text" id="content" placeholder="添加ToDo" title="請輸入此字段" /> </form> <a href="#"></a> </body> <script src="jquery-3.2.1.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript"> $(function(){ $("#content").keydown(function(e){ if (e.keyCode == 13){ $("a").text($("#content").val()); console.log($("#content").val()); } }) }) </script> </html>
葯一:
在可以不用表單Form的情況下去掉form標簽。
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8" /> 5 <meta name="viewport" content="width=device-width, initial-scale=1"> 6 <title>測試</title> 7 </head> 8 <body> 9 <label for="title">ToDoList</label> 10 <input type="text" id="content" placeholder="添加ToDo" title="請輸入此字段" /> 11 <br> 12 <a href="#"></a> 13 </body> 14 <script src="jquery-3.2.1.js" type="text/javascript" charset="utf-8"></script> 15 <script type="text/javascript"> 16 $(function(){ 17 $("#content").keydown(function(e){ 18 if (e.keyCode == 13){ 19 $("a").text($("#content").val()); 20 console.log($("#content").val()); 21 } 22 }) 23 }) 24 </script> 25 </html>
葯二:
為form添加屬性onsubmit:"return false;"。
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8" /> 5 <meta name="viewport" content="width=device-width, initial-scale=1"> 6 <title>測試</title> 7 </head> 8 <body> 9 <form onsubmit="return false"> 10 <label for="title">ToDoList</label> 11 <input type="text" id="content" placeholder="添加ToDo" title="請輸入此字段" /> 12 </form> 13 <a href="#"></a> 14 </body> 15 <script src="jquery-3.2.1.js" type="text/javascript" charset="utf-8"></script> 16 <script type="text/javascript"> 17 $(function(){ 18 $("#content").keydown(function(e){ 19 if (e.keyCode == 13){ 20 $("a").text($("#content").val()); 21 console.log($("#content").val()); 22 } 23 }) 24 }) 25 </script> 26 </html>
葯三:
給Form表單添加一個隱藏輸入框:<input id="hiddenText" type="text" style="display:none" onkeypress="searchKeywordKeyboard(event)" />。
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8" /> 5 <meta name="viewport" content="width=device-width, initial-scale=1"> 6 <title>測試</title> 7 </head> 8 <body> 9 <form> 10 <label for="title">ToDoList</label> 11 <input type="text" id="content" placeholder="添加ToDo" title="請輸入此字段" /> 12 <input id="hiddenText" type="text" style="display:none" onkeypress="searchKeywordKeyboard(event)" /> 13 </form> 14 <a href="#"></a> 15 </body> 16 <script src="jquery-3.2.1.js" type="text/javascript" charset="utf-8"></script> 17 <script type="text/javascript"> 18 $(function(){ 19 $("#content").keydown(function(e){ 20 if (e.keyCode == 13){ 21 $("a").text($("#content").val()); 22 console.log($("#content").val()); 23 } 24 }) 25 }) 26 </script> 27 </html>
