javascript中单击按钮时切换功能

我想在 JavaScript 中单击按钮“historyBtn”时切换功能。这是代码:


const expr = '';

        var history = "document.getElementById('historyBtn'). clicked == true";

        switch (expr) {

        case history:

            allMessage();

            break;

        default:

            limit_message();

        }

但是当我单击按钮“historyBtn”时,我无法将函数 limit_message() 切换到 allMessage()


编辑:在这种情况下,我想运行默认函数“limit_message”,然后当我单击“historyBtn”时将该函数切换到 allMessage


慕姐4208626
浏览 114回答 3
3回答

开满天机

<html><head>&nbsp; &nbsp; <meta charset="UTF-8">&nbsp; &nbsp; <meta name="viewport" content="width=device-width, initial-scale=1.0">&nbsp; &nbsp; <title>Document</title></head>&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; <body>&nbsp; &nbsp; &nbsp; &nbsp; <button id = "historyBtn" onclick="allMessage()">History</button>&nbsp; &nbsp; </body>&nbsp; &nbsp; <script>&nbsp; &nbsp; &nbsp; &nbsp; window.onload = limit_message();&nbsp; &nbsp; &nbsp; &nbsp; function allMessage (){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert ('In all messages - historyBtn clicked!');&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; function limit_message (){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert ('limit_message - onload');&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; </script></html>

蝴蝶不菲

function hello(ishistory) {&nbsp; if (ishistory) {&nbsp; &nbsp; console.log("History")&nbsp; }else{&nbsp; &nbsp; console.log("Limit")&nbsp; }}<button onclick="hello(true)">history</button><button onclick="hello(false)">Limit</button>只需传递一个标志即可在单击按钮时运行,如下所示。

千巷猫影

试试这个,首先获取按钮元素,然后分配一个 eventListener 并记录单击事件:let history = document.getElementById('historyBtn');history.addEventListener('click', function(e){&nbsp; console.log(e)})
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript