我希望有一个按钮充当表格上的过滤器,单击时它会执行执行过滤的函数,但再次单击时它会撤消过滤器。如果第三次单击,它会再次过滤表格,依此类推。
HTML 只是一个简单的按钮选择器:
<button id="filterButton">Click here to filter</button>
我有这个 Javascript 函数:
window.onload = function() {
document.getElementById('filterButton').onclick = function() {
FilterTable(); //this function is the one that actually does the filtering, basically setting the tr[indexOfRow].style.display="none" on some specific rows.
};
我想这样做,以便如果再次单击该按钮,它将调用一个不同的函数来撤消过滤。
我尝试在此函数的最后添加一行,使用 document.getElementById("filterButton").setAttribute("id", "将按钮的 ID 更改为
然后有另一个 JS 函数来处理 filterButtonClicked
filterButtonClicked");document.getElementById('filterButtonClicked').onclick
事件,这将撤消过滤,然后在此结束函数,将按钮的 ID 改回 fiterButton
。理论上来说,如果第三次点击该按钮,就会触发第一个 JS 函数,该函数会再次进行过滤,并将 ID 更改为 filterButtonClicked
。但在实践中,不幸的是这不起作用,它只会将 ID 更改为 filterButtonClicked
一次,后续点击不会将其更改回 filterButton
。
也许可以通过某种方式实现,如果按钮的点击次数是奇数,则执行第一个函数,如果是偶数,则执行第二个函数。但我不知道如何实现。
有更好的方法吗?
最佳答案
您正在寻找的答案非常简单......
var state = 0; //This will act as the status of the button, 0 means needs unfiltered and 1 means need filtered. It will remain one in starting to show it is unfiltered
window.onload = function() {
document.getElementById('filterButton').onclick = function() {
buttonClickFunction()
};
};
function buttonClickFunction() {
//Run this function whenever the button is clicked
if (state == 0) {
FilterTable(); //this function is the one that actually does the filtering, basically setting the tr[indexOfRow].style.display="none" on some specific rows.
state = 1; //Shows that it has been filtered
} else {
UnfilterTable(); //The function you want to run for unfilter
state = 0; //Change it back to 0 to show its unfiltered
}
}
function UnfilterTable() {
//Whatever u wanna run to unfilter
}
function FilterTable() {
//Whatever u wanna run to filter
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button id="filterButton">Click here to filter</button>
</body>
</html>
关于javascript - 如何制作一个具有两种状态的按钮,单击时根据状态触发不同的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71187328/