javascript 在 td 中获取数据属性值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27605492/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting data attribute value in td
提问by Sushil
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.
So what am I doing wrong ?
我正在尝试使用这两种方法来获取数据属性,但都返回未定义。我也得到了 td 对象,$(this)
所以这不是问题。那么我做错了什么?
回答by Mivaweb
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.
您将数据属性添加到样式中,您必须将其放置在样式属性之外。
回答by baao
<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');
回答by Rory McCrossan
That's not a data
attribute in your HTML, it's a CSS property which does not exist. Change your HTML to actually use the correct attributes then your code should work:
这不是data
HTML 中的属性,而是不存在的 CSS 属性。更改您的 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>
回答by kapantzak
<td style="text-align:center;padding: 3px 0;" data-id = "2" data-env = "PL1">