jQuery .on() method - passing argument to event handler function

前端 未结 6 1383
别那么骄傲
别那么骄傲 2021-01-31 07:49

I have the following script which does not work



        
6条回答
  •  北恋
    北恋 (楼主)
    2021-01-31 08:42

    You can pass extra data to an event handling function and can be accessed using event.data within the handler.

    $(document).on('dblclick', '#an_tnam tr', { extra : 'random string' }, function(event)
    {
        var data = event.data;
    
        // Prints 'random string' to the console
        console.log(data.extra);
    }
    

    You can also send extra data to any event you like when triggering the event from an external source using the .trigger() method

    $('#an_tnam tr').trigger('click', [{ extra : 'random string' }]);
    

    The difference with passing data to the trigger method is that it expects the handler to take extra arguments of the length of the array passed in. The above would expect the handler to have one extra argument to contain the object passed in.

    $('#an_tnam tr').on('click', function(event, obj)
    {
       // Prints 'random string' to the console
       console.log(obj.extra);
    }
    

提交回复
热议问题