0

我有一个类似于以下的标记(注意:跨度是可选的子元素):

<li class="prices">
   11.11
   <span>1.11</span>
</li>
<li class="prices">
    22.22
</li>
<li class="prices">
   33.33
   <span>3.33</span>
</li>
<li class="prices">
   44.44
</li>
<li class="prices">
   55.55
   <span>5.55</span>
</li>

我想返回范围内的价格列表及其在对象数组中的位置,所以我得到类似:{ pos: 0, price, 1.11 }, { pos: 2, price, 3.33 }, { pos: 4, price, 5.55 } 这样做的 JS 代码是什么?:)

4

2 回答 2

0

您至少需要 XPath 2.0 来执行此操作。

要获得您建议的字符串表示形式,请使用例如

string-join(
  for $li at $position in //li
  return concat("{ pos: ", $position, ", price: ", $li/span/data(), " }")[$li/span]
, ', ')

如果您更喜欢数组,您可以按顺序返回所有内容并在 JavaScript 中从中读取奇数/偶数对:

for $li at $position in //li
return ($position, $li/span/data())[$li/span]
于 2013-05-14T21:38:49.427 回答
0

Assuming that you have a container element which contains all your li.prices elements:

var container = document.getElementById("container");
var arr = [];
for (var pos = 0; pos < container.children.length; pos++) {
    var li = container.children[pos];
    var spans = li.getElementsByTagName("span");
    var price = spans.length > 0 ? spans[0].innerHTML : "";
    arr.push({pos: pos, price: price});
}

This will store the price as a string and it will use an empty string if there is no span element inside a li element.

于 2013-05-14T20:04:12.553 回答