【问题标题】:JS Prototype use a class within a classJS Prototype 在一个类中使用一个类
【发布时间】:2017-09-21 12:30:36
【问题描述】:
<td class="a-right">
  <span class="price-excl-tax">
    <span class="price">$299.00</span>
  </span>
  <br>
</td>

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

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

这就是我所拥有的:

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

【问题讨论】:

  • 你需要.在类名的开头。您应该能够使用$$('.price-excl-tax .price') 来匹配类中的类。就像 CSS 选择器一样。
  • 这本质上是一个关于 descendantchild 选择器的 CSS 问题,与 JavaScript 关系不大。
  • 我不同意它与 javascript 无关。通常我会说按类或 ID 选择。在这种特殊风格中,它没有添加 .表明类是有道理的。感谢 Barmar,我现在意识到这一点,而不是假设。

标签: javascript prototypejs


【解决方案1】:

正如 Barmar 所提到的,将 $$() 与 CSS Child Selector 一起使用(尽管基本的 Descendant Selector 也可以使用),例如 '.price-excl-tax &gt; .price'

请参见以下示例中的说明。请注意,它使用Event.observe() 处理dom:loaded 事件(PrototypeJS 独有)以确保在查询之前加载DOM。另请注意,innerHTML 属性用于获取价格元素的内容,但如果没有嵌套的 HTML 节点,也可以使用.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">$299.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
    }
}

【讨论】:

    【解决方案2】:

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

    <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">$299.00</span>
      </span>
      <br>
    </td>
    <script>
    console.log("Base price is: " + $("price-excl-tax > price"));
    </script>

    【讨论】:

    • 差不多 -- 单美元符号是“按 ID 查找”,双美元符号是“按 CSS 查找”,并且总是返回找到的对象数组(或空数组)。尝试$$('.price-excl-tax &gt; .price').first() 获取第一个,或使用each() 遍历找到的集合。
    • OP使用标签PrototypeJS,而不是jQuery;不建议包含具有不同 JavaScript 库的解决方案。
    猜你喜欢
    • 2017-08-16
    • 1970-01-01
    • 2014-07-03
    • 2014-10-06
    • 2013-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-31
    相关资源
    最近更新 更多