3

Searching Google only gives me examples with jQuery's .data() function.

However, my problem is using the jQuery's "this", as such:

$('#opener').live('click', function() {
var x = this.name;
var y = this.title;

Which takes the values from <a style='cursor:pointer' id='opener' name='$x' title='$y'>, it includes PHP variables, not that important in my question though.

Now, let's say that I want to get away from such a hacky attempt to store extra data in the HTML elements and store it properly in HTML5 by use of the data- attribute. So, the anchor would look something like:

<a style='cursor:pointer' id='opener' data-x='$x' data-y='$y'>

How would I then be able to use the "this" in jQuery like the above and get it to pick up the data? I've tried doing this.data('x') and this.data('y') but that doesn't work, and that's all I've found on the subject.

1 Answer 1

10

You need to use

$(this).data('x')

Inside the callback method, this references the dom object, but the .data() method is defined in the jQuery object wrapper for the element. So you need to wrap the dom element with jQuery using $(this).

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

1 Comment

@Blender yes If you want to support only html5 data api supported browsers, But for the time being I think it is best to delegate this to jQuery for cross-browser support

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.