JS 原型在 class 中使用 class

JS Prototype use a class within a class

<td class="a-right">
  <span class="price-excl-tax">
    <span class="price">9.00</span>
  </span>
  <br>
</td>

我在 HTML 中生成了上述代码。我需要使用 JS Prototype 来获取内部跨度的值。 "price" 的 class 有多个 span,但只有这个嵌套在 class "price-excl-tax".

http://prototypejs.org/doc/latest/Prototype/Selector/

这是我的:

console.log("Base price is: " + $$('price-excl-tax')[0].$$(span.price[0]).value);

为什么不使用子选择器。看下面的代码片段

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td class="a-right">
  <span class="price-excl-tax">
    <span class="price">9.00</span>
  </span>
  <br>
</td>
<script>
console.log("Base price is: " + $("price-excl-tax > price"));
</script>

正如 Barmar 提到的那样,使用 $$() with a CSS Child Selector (though a basic Descendant Selector 也可以,就像 '.price-excl-tax > .price' 一样。

参见下面的示例。请注意,如果没有嵌套的 HTML 节点,它也可以使用 Event.observe() for the dom:loaded event (unique to PrototypeJS) to ensure the DOM is loaded before querying it. Also note that the innerHTML property is used to get the contents of the price element, though .textContent

document.observe("dom:loaded", function() {
  var priceContainers = $$('.price-excl-tax > .price');
  if (priceContainers.length) { //Greater than 0
    console.log("Base price is: " + priceContainers[0].innerHTML);
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/prototype/1.7.3/prototype.js"></script>
<table>
  <tr>
    <td class="a-right">
      <span class="price-excl-tax">
    <span class="price">9.00</span>
      </span>
      <br>
    </td>
  </tr>
</table>

另一种方法是使用 Element.select()。类似于:

var priceExclTaxContainers = $$('.price-excl-tax');
if (priceExclTaxContainers.length) { //not empty
    var priceContainers = priceExclTaxContainers.select('.price');
    if (priceContainers.length) {
          //utilize priceContainers[0].innerHTML
    }
}