Using multiple buttons on same function that redirects to different functions

后端 未结 4 1004
暗喜
暗喜 2020-12-09 21:24

So..i\'m having this problem for couple of days not knowing how to do this,and i need help.

I have multiple buttons and clicking all of them is redirecting me to sam

4条回答
  •  一向
    一向 (楼主)
    2020-12-09 22:08

    At its simplest:

    
    
    
    
    function myFunction (button) {
        var x = button.id;
        switch (x) {
            case '1':
                myFunction1(x);
                break;
            case '2':
                myFunction2(x);
                break;
            case '3':
                myFunction3(x);
                break;
            default:
                return false;
        }
    }
    

    JS Fiddle demo.

    Though I'd amend the above to use unobtrusive JavaScript, moving the JavaScript event-handling from the elements' HTML mark-up:

    var buttons = document.getElementsByTagName('button');
    for (var i = 0, len = buttons.length; i < len; i++) {
        buttons[i].onclick = function (){
            myFunction (this);
        }
    }
    

    JS Fiddle demo.

    Or, to make it even easier (and add the event-handling to one element, rather than three):

    function myFunction (event) {
        var x = event.target.id;
        console.log(event.target, x);
        switch (x) {
            case '1':
                myFunction1(x);
                break;
            case '2':
                myFunction2(x);
                break;
            case '3':
                myFunction3(x);
                break;
            default:
                return false;
        }
    }
    
    var parent = document.getElementById('parentElementID');
    parent.addEventListener('click', myFunction);
    

    JS Fiddle demo.

    Incidentally, while it's valid (under HTML 5, not under HTML 4) to have an id that starts with a numeric character (0-9), in CSS it's difficult to target those elements (leading numeric characters require escaping, in any one of various ways); so it's still advisable to have a predictable alphabetic prefix to those ids.

    References:

    • element.addEventListener().
    • for () {...} loop.`
    • switch () {...} statement.

提交回复
热议问题