2017-02-14 20 views
0

http://www.w3schools.com/xml/tryit.asp?filename=try_xpath_select_cdnodes 嗨,這是原始示例的鏈接。我也複製粘貼在這裏的代碼。在XPath中使用xml.evaluate

<!DOCTYPE html> 
<html> 
<body> 

<p id="demo"></p> 

<script> 
var xhttp = new XMLHttpRequest(); 
xhttp.onreadystatechange = function() { 
    if (this.readyState == 4 && this.status == 200) { 
     showResult(xhttp.responseXML); 
    } 
}; 
xhttp.open("GET", "books.xml", true); 
xhttp.send(); 

function showResult(xml) { 
    var txt = ""; 
    path = "/bookstore/book/title" 
    if (xml.evaluate) {     // what is this line of code for? 
     var nodes = xml.evaluate(path, xml, null, XPathResult.ANY_TYPE, null); 
     var result = nodes.iterateNext(); 
     while (result) { 
      txt += result.childNodes[0].nodeValue + "<br>"; 
      result = nodes.iterateNext(); 
     } 
    // Code For Internet Explorer 
    } else if (window.ActiveXObject || xhttp.responseType == "msxml-document") { 
     xml.setProperty("SelectionLanguage", "XPath"); 
     nodes = xml.selectNodes(path); 
     for (i = 0; i < nodes.length; i++) { 
      txt += nodes[i].childNodes[0].nodeValue + "<br>"; 
     } 
    } 
    document.getElementById("demo").innerHTML = txt; 
} 
</script> 

</body> 
</html> 

我不明白if(xml.evaluate)聲明的目的。 它看起來像是在測試瀏覽器對XPath的支持,但它看起來好像在測試xml.evaluate是否返回true或false。

感謝

回答

0

它有兩個目的:

尋找這些文件,我已經達到了https://developer.mozilla.org/en-US/docs/Introduction_to_using_XPath_in_JavaScript,看起來很有希望瞭解它進一步。

+0

謝謝。我對第三個鏈接中討論的函數evaluate()有一個公正的理解。我不明白的是if語句中的用法。 –

+0

我不知道if(xml.evaluate)是一個函數還是對象屬性中的「評估」,或者特別是針對此if語句正在評估的內容。 –

+0

由於不使用括號,它將返回函數的「定義」而不是其執行。這樣可以有效地防止兼容性問題(請參閱第2項)。 – malarres