Phương thức attr() dùng để truy cập thuộc tính của một phần tử, chính xác là phần tử đầu tiên mà ta dùng hàm $() để chọn.
Ví dụ:
Có 1 input text:
<input type="text" name="textfield" id="textfield" value="Dau Huy" />
%3Cinput%20type%3D%22text%22%20name%3D%22textfield%22%20id%3D%22textfield%22%20value%3D%22Dau%20Huy%22%20%2F%3E
Để lấy giá trị của nó thì đơn giản như sau:
$(":submit").click(function(){
var t = $("#textfield").attr("value");
$("#test").text(t);
return false;
});
%24%28%22%3Asubmit%22%29.click%28function%28%29%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20var%20t%20%3D%20%24%28%22%23textfield%22%29.attr%28%22value%22%29%3B%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%24%28%22%23test%22%29.text%28t%29%3B%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20return%20false%3B%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%7D%29%3B
Code đầy đủ: