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

วิธีใช้ JavaScript แทนที่เนื้อหาของเอกสาร

ลองรันโค้ดด้านล่างเพื่อเรียนรู้วิธีใช้ JavaScript แทนที่เนื้อหาของเอกสาร:

ตัวอย่าง

<!DOCTYPE html>
<html>
  <body>
    <p>Click and replace this content.</p>
    <button onclick="Display()">Replace</button>
    <script>
      function Display() {
        document.open("text/html", "replace");
        document.write("<p>Demo text!</p>");
        document.close();
      }
    </script>
  </body>
</html>

คำอธิบาย: document.open("text/html", "replace") เปิดสตรีมเขียนใหม่ แทนที่หน้าปัจจุบันในประวัติ (history) document.write() เขียนเนื้อหาใหม่ document.close() ปิดสตรีม ข้อควรระวัง: การใช้ document.write หลังหน้าโหลดเสร็จจะล้างหน้าทั้งหมด ควรใช้ DOM manipulation (innerHTML, appendChild, textContent) แทนในโค้ดสมัยใหม่