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.

4

1 に答える 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).

于 2013-06-24T02:44:33.797 に答える