2017-04-24 54 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庫包含解決方案。 –