Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get onclick string with jQuery

I had to extract the 2nd parameter (array) from an onclick attribute on an image, but jQuery just returned a function onclick and not its string value as expected. So I had to use a native method.
A quick search says it may work some browsers like FF, but not IE. I use Chrome.

<img src="path/pic.png" onclick="funcName(123456,[12,34,56,78,890]);" />

I thought this would work, but it does not:

var div = $('div_id');
var onclick_string = $(div).find('img').eq(0).attr('onclick');
var onclick_part = $(onclick_string).match(/funcName\([0-9]+,(\[.*\])/)[1]; // for some reason \d doesnt work (digit)

This works

var div = $('div_id');
var onclick_string = $(div).find('img')[0].getAttributeNode('onclick').value;
var onclick_part = $(onclick_string).match(/funcName\([0-9]+,(\[.*\])/)[1]; // for some reason \d doesnt work (digit)

Is there another way of getting the 2nd parameter ?

like image 566
Kim Avatar asked Sep 24 '26 04:09

Kim


1 Answers

Why not store it in the data property?

<img src="path/pic.png" onclick="funcName(123456);" data-mydata='12,34,56,78,890' />

var div_data = $('div_id').data('mydata').split(',');
like image 117
helloandre Avatar answered Sep 26 '26 19:09

helloandre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!