引用表的顶行

时间:2010-10-22 15:49:32

标签: javascript

我希望以下脚本将表格行移动到表格的顶部。我无法弄清楚如何引用第一行的id,但是,由于ID是动态设置的,我尝试了row.insertAfter(row.first());,但是它使行消失而不是移动它。任何想法如何引用顶行?

    $(".top").click(function(){
        var row = $(this).parents("tr:first");
        if ($(this).is(".top")) {
            row.inserAfter(row.first());
        } else {
            return false;
        }
    });


<tbody id="sortable">
  <tr id="row1">
    <td><a href="" class="top">Top</a></td>
  </tr>
  <tr id="row2">
    <td><a href="" class="top">Top</a></td>
  </tr>
  <tr id="row3">
    <td><a href="" class="top">Top</a></td>
  </tr>
</tbody>

4 个答案:

答案 0 :(得分:3)

This works ...

$(".top").click(function() {
  var thisRow = $(this).parent().parent();
  var firstRow = thisRow.parent().find("tr:first").not(thisRow);
  thisRow.insertBefore(firstRow);
});

答案 1 :(得分:1)

$(".top").click(function(){
            var tr=this.parentNode.parentNode;
    tr.parentNode.insertBefore(tr.parentNode.firstChild,tr);
    tr.parentNode.removeChild(tr);   
}

答案 2 :(得分:1)

你想做这样的事吗?

$(".top").click(function(){
    var $this = $(this); // make a reference to the current element
    $.ajax({
       url: 'your/ajax/url.php',
       success: function(data) {
          // do what you want with data,
          // and then move the row on top
          // of the table, like so
          var row = $this.parents("tr");
          var first_row = row.parent().find('tr:first');
          if (row && first_row && row != first_row) {
             row.insertBefore(first_row);
          }
       }
    });
    return false; // stay on the page
});

查看http://api.jquery.com/jQuery.ajax/了解详情

答案 3 :(得分:-2)

 var row = $(this).find("tr").eq(0);
相关问题