2012-05-15 16 views
1

正如標題介紹了,這裏是我的基本XHTML頁面:我想在這個基本的xhtml頁面上使用JavaScript和XPath ...但即時通訊沒有結果?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 

<head> 
    <title>An XHTML 1.0 Strict standard template</title> 
    <meta http-equiv="content-type" content="text/html;charset=utf-8" /> 

    <script type="text/javascript"> 
     var headings = document.evaluate('//h2', document, null, XPathResult.ANY_TYPE, null); 
     var thisHeading = headings.iterateNext(); 

     var alertText = 'Level 2 headings in this document are:\n' 

     while (thisHeading) { 
      alertText += thisHeading.textContent + '\n'; 
      thisHeading = headings.iterateNext(); 
     } 

     console.log(alertText); 
    </script> 

</head> 

<body> 

<h2>… Your HTML content here …</h2> 

</body> 
</html> 

輸出是:

Level 2 headings in this document are:

+0

剛剛發現[this](http://stackoverflow.com/questions/454143/greasemonkey-xpath-returns-no-results-for-xhtml-page)...現在看着。 – wulfgarpro

回答

2

網頁瀏覽器處理HTML從上到下。您的腳本在頁面的其餘部分存在之前運行。將它向下移動,或在窗口onload事件上執行代碼。

+0

是的,大腦放屁... – wulfgarpro

1

編號1 XPath錯誤:您的內容位於名稱空間中,但您在無名稱空間中搜索它。你需要// x:h2,前綴x綁定到XHTML命名空間。

+0

謝謝你的擡頭 - ima XPath noob。 – wulfgarpro

相關問題