10

I'm using this XPath to get the value of a field:

//input[@type="hidden"][@name="val"]/@value

I get several results, but I only want the first. Using

//input[@type="hidden"][@name="val"]/@value[1]

Doesn't work. Once I have this, how do I pick up the value in Greasemonkey? I am trying things like:

alert("val " + val.snapshotItem);

But I think that's for the node, rather than the string.

4

3 回答 3

19

For the XPath, try:

//input[@type="hidden" and @name="val" and position() = 1]/@value

For use in a GreaseMonkey script, do something like this:

var result = document.evaluate(
  "//input[@type='hidden' and @name='var' and position()=1]/@value",
  document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null
);

var hiddenval = result.snapshotItem(0);

if (hiddenval)
  alert("Found: " + hiddenval.nodeValue);  
else
  alert("Not found.");

Strictly speaking: Using "position()=1" in the XPath filter is not absolutely necessary, because only the first returned result is going to be used anyway (via snapshotItem(0)). But why build a larger result set than you really need.

EDIT: Using an XPath result of the ORDERED_NODE_SNAPSHOT_TYPE type makes sure you get the nodes in document order. That means the first node of the result will also be the first node in the document.

于 2008-11-05T18:08:45.843 回答
4

Tomalak 的想法是正确的,但我会做一些不同的事情。

var result = document.evaluate(
  "//input[@type='hidden' and @name='var']",
  document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);

var input = result.iterateNext();

if (input)
  alert("Found: " + input.value);  
else
  alert("Not found.");

这样,您将指定只希望返回一个项目(在本例中为文档中的第一个项目)作为结果集的一部分。此外,您在这里获取 DOM 节点,然后读取其value属性以获取值。我发现这比通过 XPath 获取字符串值更可靠(尽管您的里程可能会有所不同)。

于 2008-11-05T19:42:59.897 回答
-1

一种可能性是在您的脚本中包含 jQuery。这将为访问元素提供更简单的语法。

// ==UserScript==
// @name           MyScript
// @namespace      http://example.com
// @description    Example
// @include        *
//
// @require     http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js
// ==/UserScript==

var input = $("input[type='hidden'][name='var']");

if (input) {
  alert("Found: " + input.val());  
} else {
  alert("Not found.");
}
于 2009-03-04T06:08:07.327 回答