简体   繁体   English

使用jQuery“this”的HTML5数据属性

[英]HTML5 data attribute with jQuery “this”

Searching Google only gives me examples with jQuery's .data() function. 仅搜索Google给出了jQuery的.data()函数示例。

However, my problem is using the jQuery's "this", as such: 但是,我的问题是使用jQuery的“this”,如下:

$('#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. 它取自<a style='cursor:pointer' id='opener' name='$x' title='$y'>的值,它包含PHP变量,但在我的问题中并不重要。

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. 现在,让我们说,我想摆脱这样一种hacky尝试,将额外数据存储在HTML元素中,并使用data-属性将其正确存储在HTML5中。 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? 那么我怎么能像上面那样在jQuery中使用“this”并获取它来获取数据呢? 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. 我已经尝试过这个this.data('x')this.data('y')但这不起作用,这就是我在这个主题上发现的全部内容。

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. 在回调方法中, this引用了dom对象,但.data()方法是在元素的jQuery对象包装器中定义的。 So you need to wrap the dom element with jQuery using $(this) . 所以你需要使用$(this)用jQuery包装dom元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM