Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 data attribute with jQuery "this"

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.

like image 399
Witold Kowelski Avatar asked Dec 28 '25 03:12

Witold Kowelski


1 Answers

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).

like image 115
Arun P Johny Avatar answered Dec 30 '25 17:12

Arun P Johny



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!