DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> HTML基礎知識 >> HTML和Xhtml
button 與 input type="button" 的區別及使用注意事項
編輯:HTML和Xhtml     

<button> 標簽的定義與用法

<button> 標簽定義一個按鈕。在 button 元素內部,你可以放置內容,比如文本或圖像,這正是它與使用 input 元素創建的按鈕之間的不同之處。

<button> 控件相比 <input type="button"> 提供了更為強大的功能和更豐富的內容。<button> 與 </button> 標簽之間的所有內容都是按鈕的內容,其中包括任何可接受的正文內容,比如文本或多媒體內容。例如可以在按鈕中放一個圖像和相關文本,做出吸引人的標記圖像。唯一禁止使用的元素是圖像映射,因為它對鼠標和鍵盤敏感的動作會干擾表單按鈕的行為。

請始終為按鈕規定 type 屬性。Internet Explorer 的默認類型是 "button",而其他浏覽器中(包括 W3C 規范)的默認值是 "submit"。所有主流浏覽器都支持 <button> 標簽。

重要事項:如果在 HTML 表單中使用 button 元素,不同浏覽器會提交不同的值。Internet Explorer 將提交 <button> 與 </button> 之間的文本,而其他浏覽器將提交 value 屬性的內容。若需在表單中創建按鈕,建議使用 input 元素。

容易踩的兩個坑

使用 <button> 標簽時很容易想當然地當成 <input type="button"> 來用,這容易導致以下錯誤:

1、取值時拿到的不是 value

通過 $('#customBtn').val() 獲取 <button id="customBtn" value="test">按鈕</button> 的 value:在 IE(IE 內核)下得到的是「按鈕」,而不是「test」;非 IE 下得到的才是「test」。這一點要和 <input type="button"> 區分開。

通過 $('#customBtn').val() 與 $('#customBtn').attr('value') 在不同浏覽器下獲得的值對比如下:

浏覽器 / 取值方式

$('#customBtn').val()

$('#customBtn').attr('value')

Firefox 13.0

test

test

Chrome 15.0

test

test

Opera 11.61

test

test

Safari 5.1.4

test

test

IE 9.0

按鈕

按鈕

驗證代碼如下:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<script type="text/javascript" src="jquery-1.4.4.min.js"></script>
<script type="text/javascript">
$(function(){
$('#test1').click(function(){
alert($('#customBtn').attr('value'));
});
$('#test2').click(function(){
alert($('#customBtn').val());
});
});
</script>
</head>
<body>
<button id="customBtn" value="test">按鈕</button>
<input type="button" id="test1" value="getattr"/>
<input type="button" id="test2" value="getval"/>
</body>
</html>

2、放在 form 裡變成了提交按鈕

無意中把 <button> 標簽放進了 <form> 標簽中,你會發現點擊這個 button 變成了提交,相當於 <input type="submit"/>。原因就是前面提到的默認 type 差異,不要把 <button> 標簽當成 form 中的普通 input 元素來用。

驗證代碼如下:

<html>
<body>
<form action="">
<button>button</button>
<input type="submit" value="inputsubmit"/>
<input type="button" value="inputbutton"/>
</form>
</body>
</html>

總結一句:在表單裡使用 button 時,務必顯式聲明 type,並清楚 IE 取的是標簽間文本而非 value,這兩點是跨浏覽器開發中最容易忽略的細節。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved