php selectnodes 参数,getElementsByTagName vs selectNodes效率 及兼容的selectNodes实现_javascript技巧...

于是就测试了下:

var stringToDom=function(text) {

var doc;

if(window.ActiveXObject) {

doc = new ActiveXObject("MSXML2.DOMDocument");

doc.loadXML(text).documentElement;

} else {

doc = (new DOMParser()).parseFromString(text,"text/xml");

}

return doc;

}

var xmlDoc=stringToDom("ab"),

c,

d1=new Date();

for(var i=0;i<100000;i++){

c=xmlDoc.getElementsByTagName("a");

}

document.write("getElementsByTagName: ",new Date()-d1);

d1=new Date();

try{

for(var i=0;i<100000;i++){

c=xmlDoc.selectNodes("a");

}

document.write("

selectNodes: ",new Date()-d1);

}catch(ex){document.write("

error:"+ex)}

在IE下selectNodes还是快多了,

可以FF下却没有这个方法,google了下,找了方法,使用XPathEvaluator来实现,下面是具体实现,不过效率就不太理想了:

if (!window.ActiveXObject) {

(function(){

var oEvaluator=new XPathEvaluator(),oResult;

XMLDocument.prototype.selectNodes = function(sXPath) {

oResult = oEvaluator.evaluate(sXPath, this, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);

var aNodes = [];

if (oResult != null) {

var oElement = oResult.iterateNext();

while (oElement) {

aNodes[aNodes.length]=oElement;

oElement = oResult.iterateNext();

}

}

return aNodes;

}

})()

}

evaluate(xpathExpression, contextNode, namespaceResolver, resultType, result);

Returns an XPathResult based on an XPath expression and other given parameters.

xpathExpression is a string representing the XPath to be evaluated.

contextNode specifies the context node for the query (see the [http://www.w3.org/TR/xpath XPath specification). It's common to pass document as the context node.

namespaceResolver is a function that will be passed any namespace prefixes and should return a string representing the namespace URI associated with that prefix. It will be used to resolve prefixes within the XPath itself, so that they can be matched with the document. null is common for HTML documents or when no namespace prefixes are used.

resultType is an integer that corresponds to the type of result XPathResult to return. Use named constant properties, such as XPathResult.ANY_TYPE, of the XPathResult constructor, which correspond to integers from 0 to 9.

result is an existing XPathResult to use for the results. null is the most common and will create a new XPathResult

完整的测试页面:

selectNodes&getElementsByTagName

本文原创发布php中文网,转载请注明出处,感谢您的尊重!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值