简体   繁体   中英

Adding dynamic text to a tag when sorting by price, ascending and descending

I've managed to add a button to my shop site which sorts the products by price ( without understanding the javascript very much).

I'd like it to update the text in button to convey to the user whether the sort by price is ascending or descending, eg: 'Sort by Price: ascending'

Here's the html of the sort button:

    <button type="button" class="btn btn-outline-secondary">
      <a class="sortByPrice" href="#art-for-sale">Sort by Price</a>
    </button>

Here's the html of the first product:

  <div class="row results">
    <div class="col-md-4 product">
      <div class="card mb-4 shadow-sm">
        <img src='images_organised_small/for_sale_small/3opera_house_night_500.jpg'>
        <div class="card-body">
          <span class="card-text title">Opera House Night</span>
          <p class="card-text price">$500</p>
          <p class="card-text description">insert artwork description here not too long but not too short!</p>
          <div class="d-flex justify-content-between align-items-center">
            <div class="btn-group">
              <button type="button" onClick="window.open('https://www.paypal.me/meredithscott4/500');" class="btn btn-sm btn-outline-secondary">Buy</button>
              <button type="button" onClick="window.open('images_organised_large/for_sale_large/3opera_house_night_500.jpg');" class="btn btn-sm btn-outline-secondary">View</button>
            </div>
            <small class="text-muted">9 mins</small>
          </div>
        </div>
      </div>
    </div>

here's the javascript

var ascending = false;

$('.tab-content').on('click', '.sortByPrice', function() {

  var sorted = $('.product').sort(function(a, b) {
    return (ascending ==
      (convertToNumber($(a).find('.price').html()) <
        convertToNumber($(b).find('.price').html()))) ? 1 : -1;
  });
  ascending = ascending ? false : true;

  $('.results').html(sorted);
});

var convertToNumber = function(value) {
  return parseFloat(value.replace('$', ''));
}

Use jQuery's .html() :

var ascending = false;

$('.tab-content').on('click', '.sortByPrice', function() {

  var sorted = $('.product').sort(function(a, b) {
    return (ascending ==
      (convertToNumber($(a).find('.price').html()) <
        convertToNumber($(b).find('.price').html()))) ? 1 : -1;
  });

  if(ascending){
    ascending = false;
    $(".sortByPrice").html("Sort by Price: descending");
  }else{
    ascending = true;
    $(".sortByPrice").html("Sort by Price: ascending");
  }


  $('.results').html(sorted);
});

var convertToNumber = function(value) {
  return parseFloat(value.replace('$', ''));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM