最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Add data attribute to table cell - Stack Overflow

programmeradmin5浏览0评论

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;
});
发布评论

评论列表(0)

  1. 暂无评论