简体   繁体   中英

How can i make a click button when do i click make sort(a-b) array and then click again to sort(b-a)

Here is my question How can i make a click button when do i click make array.sort(xy) and then click again to make array.sort(yx)

i'm already have the function but i'm confuse how to do it...

let me clarify my question: when do i click on button i make sort to array from bigger to smaller number and then i would like to press on the same button to make the array sort from smaller to bigger

here is my code:

$(".lower").click(() => {
    colorsValueMenu("highest", "spot", "gainers", "losers", "lower")
    highest = arrayCoinsD.sort(function (a, b) { return b.quote.USD.percent_change_24h - a.quote.USD.percent_change_24h })
    createCoinDiv(arrayCoinsD, arrayCoinsI)
    $(".lower").click(() => {
        colorsValueMenu("lower", "spot", "gainers", "losers", "highest")
        lower = arrayCoinsD.sort(function (a, b) { return a.quote.USD.percent_change_24h - b.quote.USD.percent_change_24h })
        createCoinDiv(arrayCoinsD, arrayCoinsI)
    })
})

it's work but just on the first & second time... i want to make it like toggleClass action for every single click

You should make your code DRY (Don't Repeat Yourself)

You can create a flag and change the operations as per the flag as:

let flag = "high";

$(".lower").click(() => {
  //   Highest
  colorsValueMenu(
    flag === "high" ? "highest" : "lower",
    "spot",
    "gainers",
    "losers",
    "lower"
  );
  highest = arrayCoinsD.sort(function (a, b) {
    return flag === "high"
      ? b.quote.USD.percent_change_24h - a.quote.USD.percent_change_24h
      : a.quote.USD.percent_change_24h - b.quote.USD.percent_change_24h;
  });

  createCoinDiv(arrayCoinsD, arrayCoinsI);
  flag = flag === "high" ? "low" : "high";
});

What you're doing right now is creating an event listener on #lower. This will do the sort(ab) like you ask, but inside that event listener you are creating another event listener, which isn't going to work. What you can do instead is create a flag like someone in the comments suggested. An example would be:

flag = false;
("#lower").click(() => {
    flag = !flag;
    if (flag) {
        //do this thing;
    } else {
        //do this other thing;
    }
}

This way, the behavior alternates whenever you click it. You can then use that to sort in different ways.

You can use the toggle method to do ascending and when you click again descending like this:

$(".lower").toggle(function(){
    // Ascending code or function
}, function (){
    // Descending code or function
})

Check the official reference here: https://api.jquery.com/toggle-event/

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