Defining JavaScript Event Object

后端 未结 4 1967
鱼传尺愫
鱼传尺愫 2021-01-15 12:24

Why am I getting an error for this piece of code?:

function catchevent() 
{
    eventSrcID=(event.srcElement)?event.srcElement.id:\'undefined\';

    eventty         


        
相关标签:
4条回答
  • 2021-01-15 12:26

    The event object is a global variable in internet explorer. (Actually a property of the global window variable)

    Firefox is simply a different design, and event is not a global variable in firefox. Instead, it is passed into the function (so you would need to change catchEvent() to accept a parameter:

    function catchEvent(event){
    

    Take a look at this artice because that is not the only problem you'll face with the event model:

    http://www.quirksmode.org/js/introevents.htmlQuirksmode article

    0 讨论(0)
  • 2021-01-15 12:31

    In Firefox and other W3C compliant browsers, the handler function will receive an event object as an argument to the function.

    IE uses a global event object.

    Here's a cross browser solution for your code.

    function catchevent( e ) {
          // reference the proper event object
        var e = e || window.event;
    
          // reference the proper target
        var srcElem = e.target || e.srcElement;
    
          // get the id of the target
        var eventSrcID = srcElem.id;
    
          // get the event type
        var eventtype = e.type;
    
          // create the status string
        var status = eventSrcID + ' has received a ' + eventtype + ' event.';
    }
    

    You'll notice I used the var keyword when creating variables. You should do this, otherwise you're creating global variables.

    Also note that the keyword this will be a reference to the element to which the handler was assigned.

    0 讨论(0)
  • 2021-01-15 12:35

    In Firefox, the first param passed to a handler is the event. So a cross browser piece of code would check for a param and use it if present. If not present, it would default to window.event, the IE way.

    0 讨论(0)
  • 2021-01-15 12:36

    you forgot to pass event in parameters.

    function catchevent(event) 
    {
        eventSrcID=(event.srcElement)?event.srcElement.id:'undefined';
    
        eventtype=event.type;
    
        status=eventSrcID+' has received a '+eventtype+' event.';
    }
    
    0 讨论(0)
提交回复
热议问题