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?

4
  • As per the HTML5 custom attributes specification, <a ... data-my-value="..." ...> is equivalent to $(...).data('myValue'). Commented Jun 27, 2013 at 14:04
  • @Phylogenesis - Not really. The .data() method can retrieve html5 data- attributes, but it can't set them. data- attributes are strings, but .data() can store other types including objects. Commented Jun 27, 2013 at 14:12
  • @nnnnnn - True. I understand that $.cache is used by jQuery to handle data(), but I thought it was worth mentioning the slight disconnect between the data key and the attribute Rifky was using. Commented Jun 27, 2013 at 14:20
  • @Phylogenesis - Ah. Right, sorry. (A disconnect of my own.) Commented Jun 27, 2013 at 14:25

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

So that mean i cannot set object in a data atribute in HTML :-(
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.

2 Comments

Is there any other alternative way to set function or object as data value in html?
you can do an eval but that is dangerous

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.