简体   繁体   English

在td中获取数据属性值

[英]Getting data attribute value in td

I am adding data attribute in td something like this : 我在td中添加数据属性,如下所示:

   <td style="text-align:center;padding: 3px 0;data-id:2;data-env:PL1;"><img  src="/VendorFeedDevUI/Content/green.png" style="width:25px" alt="Green"><div>21 Dec 14<br>23:55:00</div></td>

When I want to retrieve the same attribute in Jquery I am using below code : 当我想在Jquery中检索相同的属性时,我正在使用以下代码:

  $(".gradienttable tr td").click(function () {
        showRefreshControl();
        var id = $(this).attr('data-id');
        var env = $(this).data('env')
       });

I am trying to use both ways to get data attributes but both are returning undefined. 我正在尝试使用两种方法来获取数据属性,但是两者都返回未定义。 Also I am getting td object for $(this) so that is not an issue. 我也得到$(this) td对象,所以这不是问题。 So what am I doing wrong ? 那么我在做什么错呢?

You are using it the wrong way: 您使用错误的方式:

 <td style="text-align:center;padding: 3px 0;" data-id="2" data-env="PL1">...</td>

You add the data attributes to your styles, you have to place it outside the style attribute. 将数据属性添加到样式中,必须将其放置在样式属性之外。

   <td style="text-align:center;padding: 3px 0;" data-id="2" data-env="PL1"><!-- ... --></td>

That's how you set attributes, not within your style. 这就是您设置属性的方式,而不是您的样式。

You can then pick it up like you have done here: 然后,您可以像在这里所做的那样将其拾起:

  $(".gradienttable tr td").click(function () {
        showRefreshControl();
        var id = $(this).attr('data-id');

That's not a data attribute in your HTML, it's a CSS property which does not exist. 那不是HTML中的data属性,而是一个不存在的CSS属性。 Change your HTML to actually use the correct attributes then your code should work: 更改您的HTML以实际使用正确的属性,然后您的代码应该可以工作:

<td style="text-align: center; padding: 3px 0;" data-id="2" data-env="PL1">
   <img src="/VendorFeedDevUI/Content/green.png" style="width:25px" alt="Green" />
   <div>21 Dec 14<br>23:55:00</div>
</td>
<td style="text-align:center;padding: 3px 0;" data-id = "2" data-env = "PL1">

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

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