使用document.evaluate时未定义XPath元素/对象 [英] XPath element/object is undefined when using document.evaluate

查看:472
本文介绍了使用document.evaluate时未定义XPath元素/对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何修复常规的JavaScript代码,使其不显示"undefined"并显示输入字段的值? jQuery代码可以正常工作,并在同一页面上正确显示输入字段的值.

How can I fix the regular JavaScript code so it doesn't say "undefined" and displays the value of the input field? The jQuery code works fine and displays the input field value correctly on the same page.

常规JavaScript:

var obj = document.evaluate('//html/body/form/div[4]/label/input',document,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null); 

alert(obj.value);

JQuery 1.7.1代码:

var obj = $('html > body > form > div:nth-child(4) > label > input');

alert(obj.value);

推荐答案

document.evaluate()返回XPathResult.您可以像这样检索元素:

document.evaluate() returns an XPathResult. You can retrieve the element like this:

var obj = document.evaluate('//html/body/form/div[4]/label/input', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;

if(obj != null) {
    alert(obj.value);
}
​

这篇关于使用document.evaluate时未定义XPath元素/对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆