สมมติว่าเรามีแท็ก anchor ต่อไปนี้พร้อม URL -
<a class="demo" title="get the url" href="./mainPage.jsp/1245">href value at console</a>
เราจำเป็นต้องได้รับเฉพาะค่า URL เช่น ค่าแอตทริบิวต์ href สำหรับสิ่งนี้ ให้ใช้ attr() −
attr('href') ตัวอย่าง
ต่อไปนี้เป็นรหัส -
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<body>
<ul class="getURLDemo">
<li>
<a class="demo" title="get the url" href="./mainPage.jsp/1245">href value at console</a>
</li>
</ul>
</body>
<script>
var hrefValue = $('ul.getURLDemo li a.demo').attr('href');
console.log(hrefValue);
</script>
</html> ในการรันโปรแกรมข้างต้น ให้บันทึกชื่อไฟล์ “anyName.html(index.html)” คลิกขวาที่ไฟล์และเลือกตัวเลือก "เปิดด้วย Live Server" ในตัวแก้ไข VSCode -
ผลลัพธ์
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้บนคอนโซล -

เอาต์พุตในคอนโซล −
