document.evaluate with XPathResult.FIRST_ORDERED_NODE_TYPE返回undefined

时间:2014-12-24 07:05:40

标签: javascript xpath firebug

Firebug将xpath结果打印为未定义但未定义

function xpathTest()
{
 var div1 = document.getElementById("div1");
 var result = document.evaluate("//div[text()='Hello']", div1, null, 
                 XPathResult.FIRST_ORDERED_NODE_TYPE, null);
 console.log(result); // Firebug prints undefined
 console.log(result === undefined); // prints false
 console.log(typeof result); // prints object
 console.log(result.singleNodeValue); // prints Hello
}

这里的HTML:

<body onload="xpathTest()">
 <div id="div1">
   <div>Hello</div>
 </div>
</body>

所以实际的toString()(?)实现xpath结果不正确或者是Firebug的错?

1 个答案:

答案 0 :(得分:0)

似乎这是一个Firebug问题。

var resultDiv = document.getElementById("resultDiv");  
add("Result: " + result); // Result: [object XPathResult]
add("(result === undefined): " + (result === undefined)); 
// (result === undefined): false

add("(typeof result): " + (typeof result)); 
// (typeof result): object

add("result.singleNodeValue: " + result.singleNodeValue); 
// result.singleNodeValue: [object HTMLDivElement]

function add(content)
{
  resultDiv.innerHTML += content + "<br>";
}

请参阅JS Fiddle