Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

autofocus="autofocus" hay chỉ autofocus trong HTML5?


Câu trả lời ngắn gọn

Cả hai đều hợp lệ trong HTML5. Theo đặc điểm W3C, thuộc tính Boolean có thể viết theo 3 cách:

3 cách viết đúng chuẩn

<!-- Cách 1: Chỉ tên thuộc tính (khuyên dùng, ngắn gọn) -->
<input type="text" autofocus>

<!-- Cách 2: Giá trị trống -->
<input type="text" autofocus="">

<!-- Cách 3: Giá trị trùng tên thuộc tính -->
<input type="text" autofocus="autofocus">

Giải thích theo chuẩn W3C

"The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.

If the attribute is present, its value must either be the empty string or a value that is an ASCII case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace."

So sánh các cách viết

Cách viết Ưu điểm Nhược điểm Khuyên dùng?
autofocus Không rõ ràng cho người mới (nhìn như tên class) ✓ Có (Best practice)
autofocus="" Rõ ràng là thuộc tính Boolean, hợp lệ XML/XHTML Hơi dài ✓ Có (cho XHTML/XML)
autofocus="autofocus" Rõ ràng, tự mô tả, hợp lệ XHTML strict Dài nhất, lặp từ ✓ Có (legacy/XHTML strict)

Các thuộc tính Boolean phổ biến khác

Cùng quy tắc áp dụng cho:

disabled / disabled="" / disabled="disabled"
required / required="" / required="required"
readonly / readonly="" / readonly="readonly"
checked / checked="" / checked="checked"
selected / selected="" / selected="selected"
hidden / hidden="" / hidden="hidden"
multiple / multiple="" / multiple="multiple"
loop / loop="" / loop="loop"
controls / controls="" / controls="controls"
autoplay / autoplay="" / autoplay="autoplay"
novalidate / novalidate="" / novalidate="novalidate"
formnovalidate / formnovalidate="" / formnovalidate="formnovalidate"

Trong JavaScript (DOM API)

Dù viết thế nào trong HTML, DOM property luôn là Boolean:

const input = document.querySelector('input');
console.log(input.autofocus); // true hoặc false
console.log(input.hasAttribute('autofocus')); // true nếu có thuộc tính

// Set/remove
input.autofocus = true;  // Thêm thuộc tính
input.autofocus = false; // Xóa thuộc tính
input.removeAttribute('autofocus'); // Xóa thuộc tính

Khuyến nghị thực tế

  • HTML5 thông thường: Dùng autofocus (ngắn gọn, hiện đại)
  • XHTML / XML strict: Dùng autofocus="autofocus" hoặc autofocus=""
  • React/JSX: Bắt buộc dùng autoFocus (camelCase) với giá trị Boolean: <input autoFocus={true} />
  • Vue/Angular: Dùng autofocus directive hoặc binding