Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> HTML

HTML DOM เปรียบเทียบDocumentPosition() Method


ใช้เมธอด HTML CompareDocumentPosition() เพื่อเปรียบเทียบตำแหน่งของโหนดที่กำหนดกับโหนดอื่นๆ ในเอกสารใดๆ ชนิดส่งคืนของวิธีนี้เป็นชนิดจำนวนเต็มเพื่ออธิบายตำแหน่งในเอกสาร ค่าส่งคืนจำนวนเต็มเป็นไปตามที่ระบุ -

1: No relationship, the two nodes do not belong to the same document.
2: The first node (para1) is positioned after the second node (para2).
4: The first node (para1) is positioned before the second node (para2).
8: The first node (para1) is positioned inside the second node (para2).
16: The second node (para2) is positioned inside the first node (para1).
32: No relationship, or the two nodes are two attributes on the same element.

ไวยากรณ์

ต่อไปนี้เป็นไวยากรณ์สำหรับวิธี HTML DOM CompareDocumentPosition() -

node.compareDocumentPosition(node)

โหนดนี้เป็นโหนดประเภทวัตถุและระบุโหนดที่เราต้องการเปรียบเทียบกับโหนดปัจจุบัน

ตัวอย่าง

ให้เราดูตัวอย่างสำหรับวิธี CompareDocumentPosition() -

<!DOCTYPE html>
<html>
<body>
<p id="para1">This is a paragraph</p>
<p id="para2">This is another paragraph</p>
<p>Click the button to compare the position of the two paragraphs.</p>
<button onclick="docPosition()">POSITION</button>
<p id="Sample"></p>
<script>
   function docPosition() {
      var p1 = document.getElementById("para1").lastChild;
      var p2 = document.getElementById("para2").lastChild;
      var x = p2.compareDocumentPosition(p1);
      document.getElementById("Sample").innerHTML = x;
   }
</script>
</body>
</html>

ผลลัพธ์

สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -

HTML DOM เปรียบเทียบDocumentPosition() Method

เมื่อคลิกปุ่มตำแหน่ง -

HTML DOM เปรียบเทียบDocumentPosition() Method

ในตัวอย่างข้างต้น −

เราได้สร้างขึ้นมาสองอย่างแรก

องค์ประกอบที่มีรหัส “para1” และ “para2”

<p id="para1">This is a paragraph</p>
<p id="para2">This is another paragraph</p>

จากนั้นเราได้สร้างปุ่ม POSTION ที่จะรันเมธอด docPosition() เมื่อผู้ใช้คลิก -

<button onclick="docPosition()">POSITION</button>

docPosition() วิธีการรับทั้ง

องค์ประกอบโดยใช้เมธอด getElementById() บนวัตถุเอกสาร จากนั้นกำหนดค่าคุณสมบัติลูกสุดท้ายของทั้งสองย่อหน้าให้กับตัวแปร p1 และ p2 ตามลำดับ

จากนั้นเราเรียกเมธอด CompareDocumentPosition() บน p2 โดยมี p1 เป็นพารามิเตอร์ ซึ่งหมายความว่าเราต้องการเปรียบเทียบตำแหน่งของ p2 เทียบกับ p1 เนื่องจากที่นี่ p2 อยู่ในตำแหน่งหลัง p1 ดังนั้นผลตอบแทนที่ได้คือ 2 −

function docPosition() {
   var p1 = document.getElementById("para1").lastChild;
   var p2 = document.getElementById("para2").lastChild;
   var x = p2.compareDocumentPosition(p1);
   document.getElementById("Sample").innerHTML = x;
}