JQuery - 如何根据子属性设置父属性?

时间:2017-08-02 10:24:45

标签: jquery

我有下表:

<tbody>
<tr data-id="#ID#">
    <td class="t-Report-cell"  headers="ID">1</td>
    <td class="t-Report-cell"  headers="PARTICIPANT">61</td>
    <td class="t-Report-cell"  headers="ORDER_">1</td>
    <td class="t-Report-cell"  headers="INVITEDBY">61</td>      
    <td class="t-Report-cell"  headers="OPERATION">21</td>
</tr>
<tr data-id="#ID#">
    <td class="t-Report-cell"  headers="ID">21</td>
    <td class="t-Report-cell"  headers="PARTICIPANT">101</td>       
    <td class="t-Report-cell"  headers="ORDER_">1</td>
    <td class="t-Report-cell"  headers="INVITEDBY">61</td>      
    <td class="t-Report-cell"  headers="OPERATION">21</td>
</tr>
</tbody>

我想根据子属性标题设置属性 data-id

我写了以下代码:

var el = this.affectedElements[0];

// first part : not working
$(el).find("[headers='ID']").each(function(){
    $(this).parent().attr('data-id',$(this).data("id"));
});

// second part : works
$(el).find("tbody").sortable({
    items: 'tr'
  , containment: el
  , update: function(event,ui) { updateDisplaySeq(el); }
});

代码的第二部分使行可以排序并且它正在工作,而第一部分不起作用。

有人可以帮忙吗?

感谢。

1 个答案:

答案 0 :(得分:0)

Try this:

$(document).ready(function(){
  $("tr").each(function(index, element){
    var parentId = $(element).find('.t-Report-cell[headers="ID"]').text();
    $(element).data("id", parentId);
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table>
<tbody>
<tr data-id="">
    <td class="t-Report-cell"  headers="ID">1</td>
    <td class="t-Report-cell"  headers="PARTICIPANT">61</td>
    <td class="t-Report-cell"  headers="ORDER_">1</td>
    <td class="t-Report-cell"  headers="INVITEDBY">61</td>      
    <td class="t-Report-cell"  headers="OPERATION">21</td>
</tr>
<tr data-id="">
    <td class="t-Report-cell"  headers="ID">21</td>
    <td class="t-Report-cell"  headers="PARTICIPANT">101</td>       
    <td class="t-Report-cell"  headers="ORDER_">1</td>
    <td class="t-Report-cell"  headers="INVITEDBY">61</td>      
    <td class="t-Report-cell"  headers="OPERATION">21</td>
</tr>
</tbody>
</table>