1

in jquery if i use $("#my_button").data('my-value', { onClick: function () { my_obj_function(); } });

and in another function i do this

my-value.onClick.call() it works.

but if i try to set the data attrib in html it not working. i did this in html <a href='#' data-my-value='{"onClick":"function () { my_obj_function(); }"}'>Click me</a>

while calling my-value.onClick.call() i'm getting uncaught typeerror : object function() has no method call

what am i doing wrong?

Rifky
  • 1,444
  • 11
  • 26

2 Answers2

3

When you set a value with .data() it does not set an html attribute on the element, jQuery stores it in its own data structure. That's why you can use .data() to store functions and other objects. .data() can be used to retrieve html5 data- attributes, but not set them.

When you have an html attribute it is just a string so you'd need to eval() it or parse it somehow and pass to new Function(). This is not the way to go.

Having said that, I don't see how my-value.onClick.call() could possibly work, given that it is actually saying my minus value.onClick.call(). Assuming you had set the value with .data() you could say $("#my_button").data('my-value').onClick.call()...

If you want to set a data- attribute with jQuery you can use the .attr() method instead of .data(), with $("#my_button").attr('data-my-value', ...), but as already mentioned this will set it as a string.

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
0

Your code

<a href='#' data-my-value='{"onClick":"function () { my_obj_function(); }"}'>Click me</a>

is setting it as a string and not as an object.

Atif
  • 10,623
  • 20
  • 63
  • 96