【问题标题】:Adding dynamic text to a tag when sorting by price, ascending and descending按价格、升序和降序排序时向标签添加动态文本
【发布时间】:2021-05-17 08:16:00
【问题描述】:

我设法在我的shop site 中添加了一个按钮,该按钮按价格对产品进行排序(不太了解 javascript)。

我希望它更新按钮中的文本,以向用户传达按价格排序是升序还是降序,例如: '按价格排序:升序'

这是排序按钮的html:

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

这是第一个产品的 html:

  <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>

这里是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('$', ''));
}

【问题讨论】:

    标签: javascript html jquery sorting


    【解决方案1】:

    使用 jQuery 的.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('$', ''));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-15
      • 1970-01-01
      • 2021-01-23
      • 2012-11-08
      • 2023-03-07
      • 2013-08-16
      • 2017-11-16
      相关资源
      最近更新 更多