Jquery: pass an object to an event handler using the jquery trigger method

The following code to pass an object to an event handler does not work:

$('a.another').live('click', function(e, data) { alert(data); // **alerts '[{isMachineClick:true}]'** alert(data.isMachineClick); // **alerts 'undefined'** }); $('a.another').trigger('click', "[{isMachineClick:true}]"); 

Please take a look at this.

PS: the solution provided by the link to pass the object through the jquery trigger does not work, so we send a new stream.

+4
source share
1 answer

You only pass a string, and that more JSON inside the string is an array, not an object. Try the following:

 $('a.another').live('click', function(e, data) { alert(data[0].isMachineClick); }); $('a.another').trigger('click', [{isMachineClick:true}]); 

UPDATE I did not understand how it worked: the use of the array is correct, and each additional element becomes a different argument. This is the correct code:

 $('a.another').live('click', function(e, data, data2) { alert(data.isMachineClick); alert(data2.someOtherThing); }); $('a.another').trigger('click', [{isMachineClick:true}, {someOtherThing:false}]); 
+6
source

Source: https://habr.com/ru/post/1344042/


All Articles