Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

แสดงปีปัจจุบันอย่างเดียวใน JavaScript

ใช้ new Date().getFullYear() ดึงปีปัจจุบันมาแสดง

ตัวอย่างโค้ด

<!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>
<body>
    <h1> The Current Year=<span id="theCurrentYear"></span> </h1>

    <script>
        document.getElementById("theCurrentYear").innerHTML = new Date().getFullYear();
    </script>
</body>
</html>

วิธีรันโปรแกรม

  1. บันทึกไฟล์ชื่อ "anyName.html" หรือ "index.html"
  2. คลิกขวาที่ไฟล์ เลือก "Open with Live Server" ใน VS Code Editor

ผลลัพธ์

แสดงปีปัจจุบัน (เช่น 2024) ในหน้าเว็บ