从文本添加属性

时间:2014-10-01 18:49:09

标签: javascript jquery html

我正在尝试编写一个jQuery,将标记之间的值作为名为data-row-key =“xx”的属性

我的HTML看起来像这样:

<table id="linksgrid">
  <thead>
  </thead>
  <tbody>
    <tr class="grid-row">
      <td class="grid-cell" data-name="BrokenLink_ID">1</td>
    </tr>
    <tr class="grid-row">
      <td class="grid-cell" data-name="BrokenLink_ID">2</td>
    </tr>
  </tbody>
</table>

但我需要看起来像这样:

<table id="Table1">
  <thead>
  </thead>
  <tbody>
    <tr class="grid-row" data-row-key="1">
      <td class="grid-cell" data-name="BrokenLink_ID">1</td>
    </tr>
    <tr class="grid-row" data-row-key="2">
      <td class="grid-cell" data-name="BrokenLink_ID">2</td>
    </tr>
  </tbody>
</table>

注意到标签的添加属性

任何帮助或暗示指出我正确的方向将非常感谢,谢谢

更新 在我发布我试过的问题之前

$('td[data-name="BrokenLink_ID"]').each(function() {
  var id = $(this).text();

  var table = document.getElementById('linksgrid');
  var rows = table.rows;
  for (var i = 0, 1 = rows.lenght; i < l; i++) {
    rows[i].data = id
  }
});

6 个答案:

答案 0 :(得分:1)

$('#linksgrid tr').each(function() {
   $(this).data('row-key', $(this).text());
   // or $(this).attr('data-row-key', $(this).text());
});

答案 1 :(得分:0)

$('.grid-cell').each(function(){ // loop through each grid-cell
    var currentValue = $(this).text(); // get its text
    $(this).closest('.grid-row').attr('data-row-key', currentValue); // add the attribute to the grid-cell's parent
});

答案 2 :(得分:0)

这样的事情:

$('.grid-cell').each(function() {
    $(this).parent().attr('data-row-key', $(this).text());
});

答案 3 :(得分:0)

// run a function on each instance of .grid-row
$('.grid-row').each(function() {

    // grab the text from the current child .grid-cell
    var myAttrVal = $(this).find('.grid-cell').text();

    // add the attribute to this row
    $(this).attr('data-row-key', myAttrVal);
});

答案 4 :(得分:0)

选择所有tr元素并添加data-row-key值,如下所示:

$('#linksgrid tbody tr').data('row-key', function() {
    return $('td', this).text();
});

答案 5 :(得分:0)

$('.grid-row').each(function() {
    var no = $(this).children('td').text() 
    $(this).attr('data-row-key', no);
});