通过计算子元素中的跨度值来排序跨度

时间:2018-06-09 13:07:35

标签: javascript jquery html wordpress sorting

我有这样的代码,它是用WordPress上的短代码生成的(填充名称,价格等)

<div class="productgrid">
<span class="product">
    <span class="prodname">Product 1</span>
    <a href="#/">
        <span class="prodprices">
            <span class="prodcost">90.00</span>
            +
            <span class="prodfee">10.00</span>
        </span>
    </a>
</span>
    <span class="product">
    <span class="prodname">Product 2</span>
    <a href="#/">
        <span class="prodprices">
            <span class="prodcost">20.00</span>
            +
            <span class="prodfee">5.00</span>
        </span>
    </a>
</span>
    <span class="product">
    <span class="prodname">Product 3</span>
    <a href="#/">
        <span class="prodprices">
            <span class="prodcost">30.00</span>
            +
            <span class="prodfee">10.00</span>
        </span>
    </a>
</span>
</div>

哪个显示为

Product 1 90.00 + 10.00 

Product 2 20.00 + 5.00 

Product 3 30.00 + 10.00

由于WordPress如何处理短代码,我无法在跨度中添加任何属性。

我需要按最小到最大总价格对产品进行排序,因此每个范围内的两个范围的总和

Product 2 20.00 + 5.00 

Product 3 30.00 + 10.00 

Product 1 90.00 + 10.00

我知道在这个示例中它只是prodcost,但prodfee并不总是那么小,所以总费用就是我需要的排序依据。

1 个答案:

答案 0 :(得分:0)

这样做:

&#13;
&#13;
document.getElementById( 'sort' ).addEventListener( 'click', function() {
  var els = document.querySelectorAll( '.product' );

  for ( var i = 0, val = []; i < els.length; i++ ) {
    val[ i ] = { index: i, value: Number( document.querySelectorAll( '.prodcost' )[ i ].innerText ) + Number( document.querySelectorAll( '.prodfee' )[ i ].innerText ) };
  }

  val.sort( function( a, b ) {
    return a.value > b.value ? 1 : a.value == b.value ? 0 : -1
  } )

  for ( var i = 0, str = ''; i < val.length; i++ ) {
    str += '<div class="product">' + els[ val[ i ].index ].innerHTML + '</div>'
  }

  document.querySelector( '.productgrid' ).innerHTML = str
} )
&#13;
<input id="sort" type="button" value="Sort">

<div class="productgrid">
  <div class="product">
    <span class="prodname">Product 1</span>
    <a href="#/">
      <span class="prodprices">
        <span class="prodcost">90.00</span> + <span class="prodfee">10.00</span>
      </span>
    </a>
  </div>
  <div class="product">
    <span class="prodname">Product 2</span>
    <a href="#/">
      <span class="prodprices">
        <span class="prodcost">20.00</span> + <span class="prodfee">5.00</span>
      </span>
    </a>
  </div>
  <div class="product">
    <span class="prodname">Product 3</span>
    <a href="#/">
      <span class="prodprices">
        <span class="prodcost">30.00</span> + <span class="prodfee">10.00</span>
      </span>
    </a>
  </div>
</div>
&#13;
&#13;
&#13;