問題:
button 按鈕在不設置 type 屬性時,在不同的瀏覽器作用不一樣。舉個例子:
html:
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/> <meta name="renderer" content="webkit"/> <meta name="keywords" content=""/> <meta name="description" content=""/> <title>button按鈕的一些問題</title> </head> <body> <form action="result.php" method="post"> <input type="text" name="txt" placeholder="隨便輸入點什么吧!" autocomplete="off"/> <button>button點擊提交</button> </form> </body> </html>
result.php:
<?php echo $_POST['txt'] ?>
我們發現,在 ie8 以上包括 ie8 點擊按鈕可以正常提交表單,但是在 ie6 和 ie7 下面,點擊按鈕沒有反應。
原因:
為什么會有差異?因為 button 按鈕沒有設置 type 屬性,在不同的瀏覽器中解析 button 的 type 類型不盡相同。
通過 w3school 可以發現,我們需要始終為 button 按鈕規定 type 屬性。Internet Explorer(經測試是 ie6 和 ie7)的默認類型是 "button",而其他瀏覽器中(包括 W3C 規范)的默認值是 "submit"。具體內容點此了解。
最后我們修改下 demo:
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/> <meta name="renderer" content="webkit"/> <meta name="keywords" content=""/> <meta name="description" content=""/> <title>button按鈕的一些問題</title> </head> <body> <form action="result.php" method="post"> <input type="text" name="txt" placeholder="隨便輸入點什么吧!" autocomplete="off"/> <button type="button">button按鈕type為button</button> <button type="submit">button按鈕type為submit</button> </form> </body> </html>
PS:
寫這篇文章的目的在於提醒自己在使用 button 時需要為標簽指定相應的 type 類型。