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

วิธีเพิ่มค่า Counter (ตัวนับ) ด้วย JavaScript

ใช้คุณสมบัติ counterIncrement เพื่อเพิ่มค่าตัวนับ CSS ซึ่งมักใช้ร่วมกับ pseudo-elements เช่น ::before เพื่อสร้างหมายเลขอัตโนมัติ

ตัวอย่าง

<!DOCTYPE html>
<html>
  <head>
    <style>
      h2 {
        counter-increment: section;
      }
      h2:before {
        content: counter(section) " Quiz ";
      }
    </style>
  </head>
  <body>
    <h1>Quizzes</h1>
    <p>Change the counterIncrement</p>
    <h2>Ruby</h2>
    <h2 id="myID">Java</h2>
    <h2>PHP</h2>
    <h2>Perl</h2>
    <button onclick="display()">Update Counter Increment</button>
    <script>
      function display() {
        document.getElementById("myID").style.counterIncrement = "subsection";
      }
    </script>
  </body>
</html>