javascript - 如何制作一个具有两种状态的按钮,单击时根据状态触发不同的功能

标签 javascript html

我希望有一个按钮充当表格上的过滤器,单击时它会执行执行过滤的函数,但再次单击时它会撤消过滤器。如果第三次单击,它会再次过滤表格,依此类推。

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 更改为 filterButtonClicked filterButtonClicked"); 然后有另一个 JS 函数来处理 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/

相关文章:

javascript - 有没有办法在 MVC 中的 View 上使用 ajax 调用来使用新信息刷新页面?

javascript - jQuery 在特定位置插入字符

html - 将容器设置为固定高度和可滚动

javascript - 在 JavaScript 中确定流体宽度或固定宽度

html - 第 1 行中的 css 静态标题与表行不对齐

javascript - 如何在 Angular 中构建延迟加载侧边栏?

javascript - Quasar - 垂直滚动条不能在超过 600 像素的宽度上工作

javascript - 鼠标移动页面背景渐变变化

javascript - :blank selector not working on checkbox jQuery Validate()

javascript - 在 Android 上禁用自动完成