首页 > 解决方案 > 如何根据按钮元素的点击事件触发的切换状态呈现不同的文本内容?

问题描述

我有一个按钮,单击该按钮时,会将文本从“报告问题”更改为“关闭”并打开一个下拉文本输入,当再次单击该按钮时,它仍设置为“关闭”,而我希望它返回'报告一个问题'。我只知道如何一键触发 2 个事件,而这将是一个两键操作。关于解决此问题的最佳方法的任何想法?

function change() {
  document.getElementById("myBtnToReportABug").innerHTML = "Close";
}
<button id="myBtnToReportABug" onclick="change()" type="button" class="btn btn-secondary float-right" data-toggle="myModal" data-target="#myModal"> Report A Problem </button>

标签: javascriptevent-handlingstatetogglebutton

解决方案


我会使用另一个数据属性来跟踪切换状态,例如data-button-state作为新属性:

function change() {
    var button = document.getElementById("myBtnToReportABug");
    var buttonState = button.dataset.buttonState;
    var buttonText;
    var buttonState;

    if (buttonState === 'report') {
        buttonText = "Close";
        buttonState = "close";
    } else {
        buttonText = "Report A Problem";
        buttonState = "report"
    }

    button.innerHTML = buttonText;
    button.dataset.buttonState = buttonState;
}
<button
    id="myBtnToReportABug"
    onclick="change()"
    type="button"
    class="btn btn-secondary float-right"
    data-toggle="myModal"
    data-target="#myModal"
    data-button-state="report"
>
        Report A Problem
</button>

if使用这种方法,您可以拥有多个状态,只需在每个语句中定义您想要对这些状态执行的操作:)


推荐阅读