jQuery: attr() method
Phương thức attr() cho phép bạn lấy giá trị của một thuộc tính bất kỳ của phần tử HTML.
Cú pháp:
$(Bộ_chọn).attr( "Tên_thuộc_tính"); //Lấy giá trị của thuộc tính
$(Bộ_chọn).attr( "Tên_thuộc_tính","Giá_trị"); //Đặt giá trị cho thuộc tính
Ví dụ: Ví dụ này sẽ demo cách dùng phương thức attr() để lấy giá trị của thuộc tính href của phần tử <a>.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="http://ajax.googleapis. com/ajax/libs/jquery/1.11.0 /jquery.min.js">
</script>
<script>
$(function(){
$("#input").click(function(){
alert("Giá trị của thuộc tính href:\n" + $("#a2").attr("href"));
$("#a2").html("<em> http://v1study.com</em>");
$("#a2").attr("href", "http://v1study.com");
alert("Sau khi đặt lại giá trị cho thuộc tính href:\n" + $("#a2").attr("href"));
});
});
</script>
</head>
<body>
<p><a href= "http://demo.v1study.com" id="a2"> http://demo.v1study.com</a></p>
<input id="input" type="button" value="Lấy giá trị của thuộc tính 'href'">
</body>
</html>
Ví dụ dưới đây bạn sẽ thấy phương thức attr() có thể đặt cùng lúc nhiều giá trị cho nhiều thuộc tính của phần tử HTML.
Ví dụ:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="http://ajax.googleapis. com/ajax/libs/jquery/1.11.0 /jquery.min.js">
</script>
<script>
$(function(){
$("input").click(function(){
$("#a").text( "http://v1study.com");
$("#a").attr({
"href":"http://v1study.com",
"title":"v1study.com"
});
});
});
</script>
</head>
<body>
<p>href hiện tại: <a href= "http://demo.v1study.com" title="demo.v1study.com" id="a"> http://demo.v1study.com</a></p>
<input id="input" type="button" value="Đặt lại thuộc tính href và title">
<p>Bạn hãy chạm vào link để thấy title hiện tại.</p>
</body>
</html>
Tạo hàm callback cho phương thức attr()
Cú pháp:
$(Bộ_chọn).attr( "Tên_thuộc_tính", function(Chỉ_mục,Giá_trị_cũ){
return Giá_trị_mới;
});
Ví dụ:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="http://ajax.googleapis. com/ajax/libs/jquery/1.11.0 /jquery.min.js">
</script>
<script>
$(function(){
$("input").click(function(){
$("#a").attr("href", function(i,oldvalue){
alert('Giá trị cũ: ' + oldvalue);
$(this).text( "http://v1study.com");
return "http://v1study.com";
});
});
});
</script>
</head>
<body>
<p>href hiện tại: <a href= "http://demo.v1study.com" id="a"> http://demo.v1study.com</a></p>
<input type="button" value="Đặt lại giá trị href">
</body>
</html>