Is it possible to add a data attribute to a table cell using jquery? I have the following but it doesn't add a data-attribute to the td
.
$("td.row").each(function( index ) {
$(this).data("rowid",index);
});
Any ideas?
Is it possible to add a data attribute to a table cell using jquery? I have the following but it doesn't add a data-attribute to the td
.
$("td.row").each(function( index ) {
$(this).data("rowid",index);
});
Any ideas?
Share Improve this question asked Jul 14, 2013 at 23:54 SpencerSpencer 6422 gold badges12 silver badges26 bronze badges 7- Do you want the actual attribute to show up? – Shawn31313 Commented Jul 14, 2013 at 23:55
-
Because if you do, then you need to use:
$(this).attr("data-rowid", index);
– Shawn31313 Commented Jul 14, 2013 at 23:55 -
I used the inspect element tool in Chrome, but the data-rowid attributes don't appear in the
td
using the jQuery code. – Spencer Commented Jul 14, 2013 at 23:57 -
data()
stores atribitrary data on the element, it does not set the data attribute, but it can be confusing asdata()
will get the data attribute in some cases. – adeneo Commented Jul 14, 2013 at 23:57 -
.data()
allows you to store data associated with an element and it does allow you to get the data from already setdata-*
attributes. But it doesn't actually adddata-*
attributes to an element. – Shawn31313 Commented Jul 14, 2013 at 23:58
1 Answer
Reset to default 6.data()
allows you to store data associated with an element. It does allow you to get the data from element with an already set data-*
attribute, but it doesn't actually allow you to add data-*
attributes to an element.
.attr()
allows you to add this attribute though.
$("td.row").each(function( index ) {
$(this).attr("data-rowid", index);
});
You can also use @CrazyTrain's solution which seems a little more efficient:
$("td.row").attr("data-rowid", function(index) {
return index;
});
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744298800a4567396.html
评论列表(0条)