Phương thức so sánh DOM XMLDocumentPosition ()
❮ Đối tượng nút
Thí dụ
Đoạn mã sau tải " books.xml " vào xmlDoc và so sánh vị trí của hai nút (phần tử <book> đầu tiên và thứ ba) trong phân cấp DOM:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "books.xml", true);
xhttp.send();
function myFunction(xml) {
var xmlDoc = xml.responseXML;
var x =
xmlDoc.getElementsByTagName('book')[0];
var y =
xmlDoc.getElementsByTagName('book')[2];
document.getElementById("demo").innerHTML =
x.compareDocumentPosition(y);
}
Đầu ra của đoạn mã trên sẽ là:
4
Hầu hết các trình duyệt sẽ coi khoảng trắng trống hoặc các dòng mới là nút văn bản, IE 9 trở về trước thì không. Vì vậy, trong ví dụ trên, hầu hết các trình duyệt sẽ xuất ra 4, trong khi IE 9 trở về trước sẽ xuất ra 2.
Định nghĩa và Cách sử dụng
Phương thức CompareDocumentPosition () so sánh vị trí của hai nút trong hệ thống phân cấp DOM (tài liệu).
Hỗ trợ trình duyệt
Phương thức CompareDocumentPosition () được hỗ trợ trong tất cả các trình duyệt chính.
Lưu ý: Internet Explorer 9 trở về trước không hỗ trợ phương pháp này.
Cú pháp
nodeObject.compareDocumentPosition(node)
Thông số
Parameter | Type | Description |
---|---|---|
node | Node object | Required. Specifies the node to compare with the current node |
Giá trị trả lại
Type | Description |
---|---|
Number | A Number representing where the two nodes are positioned compared to each other. The possible return values
are:
1 - No relationship, the two nodes do not belong to the same document. 2 - The specified node precedes the current node. 4 - The specified node follows the current node. 8 - The specified node contains the current node. 16 - The specified node is contained by the current node. 32 - The specified and the current node have no common container node or the two nodes are different attributes of the same node. Note: The return value could also be a combination of values. E.g. a return value of 20 means that the specified node is contained by the current node (16) AND the specified node follows the current node (4). |
Chi tiết kỹ thuật
Phiên bản DOM | Đối tượng nút cấp 3 cốt lõi |
---|
❮ Đối tượng nút