2017-04-24 50 views
0
<td class="a-right"> 
    <span class="price-excl-tax"> 
    <span class="price">$299.00</span> 
    </span> 
    <br> 
</td> 

我在生成HTML中有上述代码。我需要使用JS Prototype来获取内部跨度的值。 “价格”类有多个跨度,但只有这一个嵌套在类“价格不含税”的范围内。JS原型使用一个类内的类

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

这是我有:

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

您需要'''在类名的开头。您应该可以使用$$('。price-excl-tax .price')'来匹配类中的类。就像CSS选择器一样。 – Barmar

+0

这实际上是一个关于[后代](https://developer.mozilla.org/en-US/docs/Web/CSS/Descendant_selectors)或[child](https://developer.mozilla.org/en)的CSS问题-US/docs/Web/CSS/Child_selectors)选择器,与JavaScript很少有关。 –

+0

我不同意它与JavaScript没有多大关系。通常我会说按类或ID选择。在这种特殊的风格,它没有如此添加。表明上课会有意义。感谢Barmar,我现在意识到这一点,而不是假设。 – camdixon

回答

0

正如Barmar提到的,使用$$()用CSS Child Selector(虽然基本Descendant Selector将工作以及)像'.price-excl-tax > .price'

请看下面的例子。请注意,它将Event.observe()用于dom:loaded事件(PrototypeJS特有),以确保DOM在查询之前已加载。另请注意,innerHTML属性用于获取price元素的内容,但如果没有嵌套的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 
    } 
} 
1

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

<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>

+0

几乎 - 单一的美元符号是“通过ID查找”,双美元符号是“通过CSS查找”,并且总是返回找到的对象(或空数组)的数组。尝试'$$('。price-excl-tax> .price')。first()'获取第一个,或者用'each()'遍历找到的集合。 – Walter

+0

OP使用标签[PrototypeJS](http://stackoverflow.com/questions/tagged/prototypejs),而不是jQuery;不建议使用不同的JavaScript库包含解决方案。 –