0

好的,所以我正在尝试对网页上的项目进行排序,我使用 getElementsByClassName 并将其保存为节点列表或数组,我不确定,但是当我使用 console.log 时,它会显示 h2 价格、h2 价格、h2 价格。我只想要商品价格,以便对它们进行排序当我查看 innerHTML 它具有我想要的商品价格时,我如何得到它而不是“h2 价格”,以便我可以删除 $,然后首先按最高或最低价格排序?

这是我的一些 HTML:

<div class="col-sm-4">
<div class="product-image-wrapper">
<div class="single-products">
  <div class="productinfo text-center">
    <img src="images\site_images\bag3.jpg" alt="" height="249" />
    <h2 class="price">$881.10</h2>
    <h5>Authentic New Gucci ($1690) Micro-GG "Vernice" Crossbody w/Strap #309617, NWT</h5>
    <a href="#" class="btn btn-default add-to-cart"><i class="fa fa-shopping-cart"></i>Add to Cart</a>
  </div>
  <div class="col-sm-4">
    <div class="product-image-wrapper">
      <div class="single-products">
        <div class="productinfo text-center">
          <img src="images\site_images\bag4.jpg" alt="" height="249" />
          <h2 class="price">$569.05</h2>
          <h5>AUTHENTIC NWT ($819) Gucci GG Large Brown Denim Tassell Tote #336660, w/Gft Rcpt</h5>
          <a href="#" class="btn btn-default add-to-cart"><i class="fa fa-shopping-cart"></i>Add to Cart</a>
        </div>

        <div class="col-sm-4">
          <div class="product-image-wrapper">
            <div class="single-products">
              <div class="productinfo text-center">
                <img src="images\site_images\bag5.jpg" alt="" height="249" />
                <h2 class="price">$559.00</h2>
                <h5>Authentic Gucci GG Micro-Guccissima Leather Tote #309613 w/Gft Rcpt,NWT</h5>
                <a href="#" class="btn btn-default add-to-cart"><i class="fa fa-shopping-cart"></i>Add to Cart</a>
              </div>
              <button onclick="myFunction()">Try it</button>
              <p id="demo"></p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

还有我的 Javascript:

function myFunction() {
    var items = document.getElementsByClassName('price');
    var prices = [];
}
4

1 回答 1

2

尝试使用Array.prototype.slice(),Array.prototype.map()转换HTMLCollectionArray, Number(), String.prototype.replace()with RegExp /\$/,Array.prototype.sort()

function myFunction() {
  return Array.prototype.slice.call(document.getElementsByClassName("price"))
  .map(function(el) {return Number(el.innerHTML.replace(/\$/, ""))})
  .sort();
}
于 2015-12-26T03:40:23.633 回答