Handling “onclick” event with pure JavaScript

后端 未结 3 649
旧时难觅i
旧时难觅i 2020-11-29 07:23

So this is really straight forward but I\'m still fairly new to JavaScript and just found JSFiddle. I\'m trying to find the element with the getElementById() t

3条回答
  •  爱一瞬间的悲伤
    2020-11-29 08:05

    You have a Error here

    btnRush should be Rushbtn

    This is a example of cross browser event's I just made (not tested) )

    var addEvent = function( element, type, callback, bubble ) { // 1
        if(document.addEventListener) { // 2
            return element.addEventListener( type, callback, bubble || false ); // 3
        }
        return element.attachEvent('on' + type, callback ); // 4
    };
    
    
    
    var onEvent = function( element, type, callback, bubble) { // 1
        if(document.addEventListener) { // 2
            document.addEventListener( type, function( event ){ // 3
                if(event.target === element || event.target.id === element) { // 5
                    callback.apply(event.target, [event]); // 6
                }
            }, bubble || false);
        } else {
            document.attachEvent( 'on' + type, function( event ){ // 4 
                if(event.srcElement === element || event.srcElement.id === element) { // 5
                    callback.apply(event.target, [event]); // 6
                }
            });
        }
    
    };
    

    Steps

    1. Create a function that accepts 4 values ( self explaining )
    2. Check if the browser supports addEventListener
    3. Add event on the element
    4. else add event on the element for older IE
    5. Check that the (clicked) element is = to the passed element
    6. call the callback function pass the element as this and pass the event

      The onEvent is used for event delegation. The addEvent is for your standard event.

      here's how you can use them

    The first 2 are for dynamically added elements

    onEvent('rushBtn', 'click', function(){
        alert('click')
    });
    
    var rush = document.getElementById('rushBtn');
    
    onEvent(rush, 'click', function(){
        alert('click');
    });
    
    // Standard Event
    addEvent(rush, 'click', function(){
        alert('click');
    });
    

    Event Delegation is this basically.

    Add a click event to the document so the event will fire whenever & wherever then you check the element that was clicked on to see if it matches the element you need. this way it will always work.

    Demo

提交回复
热议问题