获取所有span的内容与同一个类

时间:2017-02-08 13:24:03

标签: javascript jquery arrays

我遇到的问题是我正在尝试使用相同的类获取所有span的内容。

那是相关的html:

    @foreach($products as $product
        <div class="media-body">
             <h4 class="media-heading">{{ $product->title }}</h4>
             <p>{{ $product->short_description }}</p>
             <div class="pull-right">
                  <span class="priceCell">{{$product->sales_price}}</span>€
                  <span>Quantities: </span><span class="quantitie">{{ $product->quantity }}      </span>
                  <br>
             </div>
         </div>
    @endforeach

$ products变量有6种不同的产品。所以6个不同的数量。 我需要不同数量的数组,如下所示:

var quantity = [25,20,15,10,5,1];

当前的js:

var quantities = document.getElementsByClassName("quantities");
alert(quantities) -- gives : html collection 

我需要这样的数量数组:[10,5,3,1]

因为我想在这段代码中使用它:

for (var q = 0; q < quantitys.length; q++) {
    endPrice += (parseInt(quantities[q]) * parseFloat(prices[q]));
}

价格变量也如下所示:[15.00,20.00,...]

等等......但没有任何对我有用。有人可以帮助我吗?谢谢!

1 个答案:

答案 0 :(得分:1)

尝试使用简单的东西

var spans = document.getElementsByClassName("quantities");

for(i=0;i<spans.length;i++)
{
  alert(spans[i].innerHTML);
}
<span class="quantities">A</span>
<span class="quantities">B</span>
<span class="quantities">C</span>
<span class="quantities">D</span>
<span class="quantities">E</span>

数组的简单示例

function getSpanDataByClass(className){
  var spans = document.getElementsByClassName(className),
      result = [];
  
  if(!spans){
    //no data 
  }
  
  for(var i = 0; i < spans.length; i++){
    result.push(spans[i].innerHTML);
  }

  return result;
};

function runDebug(){
  var spanInnerData = getSpanDataByClass("quantities");
  
  alert(spanInnerData);
};

runDebug();
<span class="quantities">A</span>
<span class="other">B</span>
<span class="quantities">C</span>
<span class="other">X</span>
<span class="quantities">Y</span>
<span class="quantities">Z</span>