簡體   English   中英

按價格、升序和降序排序時向標簽添加動態文本

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

我設法在我的商店網站上添加了一個按價格對產品進行分類的按鈕(不太了解 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('$', ''));
}

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM