這是我的問題,當我單擊 make array.sort(xy) 然后再次單擊 make array.sort(yx) 時,如何制作單擊按鈕
我已經有了這個功能,但我很困惑如何去做...
讓我澄清一下我的問題:我什么時候點擊按鈕,我將陣列從大到小排序,然后我想按下同一個按鈕,讓陣列從小到大排序
這是我的代碼:
$(".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)
})
})
它的作業,但只是在第一次和第二次......我想讓它像每次點擊的toggleClass動作一樣
uj5u.com熱心網友回復:
你應該讓你的代碼 DRY (Don't Repeat Yourself)
您可以按照以下方式創建flag和更改操作flag:
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";
});
uj5u.com熱心網友回復:
您現在正在做的是在#lower 上創建一個事件偵聽器。這將按照您的要求進行排序(ab),但是在該事件偵聽器中,您正在創建另一個事件偵聽器,這將不起作用。您可以做的是像建議的評論中的某個人一樣創建一個標志。一個例子是:
flag = false;
("#lower").click(() => {
flag = !flag;
if (flag) {
//do this thing;
} else {
//do this other thing;
}
}
這樣,每當您單擊它時,行為就會交替。然后,您可以使用它以不同的方式進行排序。
uj5u.com熱心網友回復:
您可以使用該toggle方法進行升序,然后再次單擊時降序如下:
$(".lower").toggle(function(){
// Ascending code or function
}, function (){
// Descending code or function
})
在此處查看官方參考:https : //api.jquery.com/toggle-event/
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/364814.html
標籤:javascript 查询 数组 排序 切换按钮
