ในการรับค่าของแอตทริบิวต์ HTML ให้ลองทำดังนี้:
$("#demo").attr("tabindex") วิธี attr() สามารถใช้เพื่อดึงค่าของแอตทริบิวต์จากองค์ประกอบแรกในชุดที่ตรงกันหรือตั้งค่าแอตทริบิวต์ไปยังองค์ประกอบที่ตรงกันทั้งหมด
คุณยังสามารถใช้วิธี hasAttribute() เพื่อดูว่ามีแอตทริบิวต์สำหรับองค์ประกอบหรือไม่
ตัวอย่าง
ลองเรียกใช้โค้ดต่อไปนี้เพื่อเรียนรู้วิธีใช้ hasAttribute() วิธีการ:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('button').on('click', function() {
if (this.hasAttribute("style")) {
alert('True')
} else {
alert('False')
}
})
});
</script>
</head>
<body>
<button class = 'button' style = 'background-color:blue;'>
Button
</button>
<button class = 'button'>
Button 2
</button>
</body>
</html>