简体   繁体   English

单击 javascript 中的按钮时切换 function

[英]Switch function when click button in javascript

I want to switch function when button 'historyBtn' clicked in javascript.当在 javascript 中单击按钮“historyBtn”时,我想切换 function。 Here is the code:这是代码:

const expr = '';
        var history = "document.getElementById('historyBtn'). clicked == true";
        switch (expr) {
        case history:
            allMessage();
            break;
        default:
            limit_message();
        }

But when i click button 'historyBtn' i cant switch function limit_message() to allMessage()但是当我单击按钮'historyBtn'时,我无法将 function limit_message() 切换到 allMessage()

Edit: in this case i want to run function 'limit_message' for default function, and then switch that function to allMessage when i click 'historyBtn'编辑:在这种情况下,我想为默认 function 运行 function 'limit_message',然后在单击 i 时将 function 'B'history 切换到 allMessage

Try this, first get the button element, then assign an eventListener and logs the click event:试试这个,首先获取按钮元素,然后分配一个 eventListener 并记录点击事件:

 let history = document.getElementById('historyBtn'); history.addEventListener('click', function(e){ console.log(e) })

 function hello(ishistory) { if (ishistory) { console.log("History") }else{ console.log("Limit") } }
 <button onclick="hello(true)">history</button> <button onclick="hello(false)">Limit</button>

Just pass a flag to function on button click like this.只需像这样在按钮单击时将标志传递给 function。

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

    
    <body>
        <button id = "historyBtn" onclick="allMessage()">History</button>
    </body>
    <script>
        window.onload = limit_message();
        function allMessage (){
            alert ('In all messages - historyBtn clicked!');
        }
        
        function limit_message (){
            alert ('limit_message - onload');
        }
            
    </script>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM