Javascript 对来自XPathEvaluator的对象使用setAttribute()
我在Javascript 对来自XPathEvaluator的对象使用setAttribute(),javascript,css,firefox,xpath,Javascript,Css,Firefox,Xpath,我在xpatheevaluator()对象上使用evaluate()函数时遇到一些问题。 我的代码如下所示: var evaluator = new XPathEvaluator(); var result = evaluator.evaluate("//div[@id='header']/div[4]", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null); result.setAttribute("style", "backg
xpatheevaluator()
对象上使用evaluate()
函数时遇到一些问题。
我的代码如下所示:
var evaluator = new XPathEvaluator();
var result = evaluator.evaluate("//div[@id='header']/div[4]", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
result.setAttribute("style", "background: red; outline: blue solid thick;");
evaluate()
不返回可由setAttribute()函数使用的对象。
我读书。
如何获取可在其上使用的正确对象setAttribute()
?您可以在元素节点上使用setAttribute
。evaluate
方法不返回元素节点或节点列表,而是提供一个对象。所以你想要
var div = document.evaluate("//div[@id='header']/div[4]", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
if (div !== null) {
div.setAttribute("attribute-name", "attribute-value");
}
键入时:try{var result=evaluator.evaluate(xpath,document,null,XPathResult.FIRST_ORDERED_NODE_type,null).singleNodeValue;}catch(err){alert(“ERROR!\n”+err.message);}
I get:evaluator.evaluate不是一个函数,我只会使用DOM文档对象上公开的evaluate
方法,如我的帖子所示。我还准备了Firefox、Opera和Chrome,对我来说效果很好。因此,我建议对(…)进行评估。据我所知,singleNodeValue
很好。至于使用setAttribute
,我更喜欢使用DOM属性,例如element.align='right'
或element.style.backgroundColor='red'
,但是对于FirefoxsetAttribute
也应该这样做(一旦代码选择了元素节点)。