javascript - Add data attribute to table cell - Stack Overflow

Is it possible to add a data attribute to a table cell using jquery? I have the following but it doesn&

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 as data() 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 set data-* attributes. But it doesn't actually add data-* attributes to an element. – Shawn31313 Commented Jul 14, 2013 at 23:58
 |  Show 2 more ments

1 Answer 1

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

相关推荐

  • javascript - Add data attribute to table cell - Stack Overflow

    Is it possible to add a data attribute to a table cell using jquery? I have the following but it doesn&

    7天前
    70

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信