Jquery move 表行但不 move 表头

标签 jquery sorting row move

我的表格行可以上下 move ,但我的问题是数据表行取代了表格标题(第一行)。

我想要一个固定的第一行,这样当您单击向上箭头时,您就不会向上 move 该行来替换标题。

我尝试了一些条件逻辑来检查当前行是否是表的第一行,但它不起作用。

$(document).ready(function(){

<!--- Move: click to move rows up or down --->
$(".up,.down").click(function(){
var row = $(this).parents("tr:first");

<!-- this var does not work -->
var firstrow = $('table')[0].rows[0]; 

<!-- Check that is not the first row NEEDS FIXED -->
if (row != firstrow){

if ($(this).is(".up")) {
row.insertBefore(row.prev());
} else {
row.insertAfter(row.next());
}
}
});
});

<table>
<tr>
<td>Do Not Replace Me</td>
<td >&nbsp;</td>
</tr>
<tr>
<td>Two</td>
<td>
<a href="#" class="up">Up</a>
<a href="#" class="down">Down</a>
</td>
</tr>
<tr>
<td>Three</td>
<td>
<a href="#" class="up">Up</a>
<a href="#" class="down">Down</a>
</td>
</tr>
</table>

表格必须保持原样,我不能将 td 更改为 th 或类似的内容。

我希望有一种方法可以修复这两行代码。

最佳答案

正如我想您知道的那样(考虑到您的免责声明,html 必须“保持原样...”),如果您可以将标题/第一行放入 thead 中,则会容易得多。元素和余数为 tbody ,但一种使用 html 的方法“按原样:”

$(".up,.down").click(function() {
    var row = $(this).parents("tr:first");

    var firstrow = $('table tr:first');

    if ($(this).is(".up") && row.prevAll().length > 1) {
        row.insertBefore(row.prev());
    }
    else if ($(this).is(".down") && row.nextAll().length > 0) {
        row.insertAfter(row.next());
    }
    else {
        return false;
    }
});

JS Fiddle demo .

顺便说一句,您的脚本可能会从注释中生成错误(尽管我确实怀疑这些错误是为了我们的利益而添加的,而不是在您实际的 JavaScript 中)语法:

<!-- comment text -->

是html语法,并且在<script></script>的范围内标签无效,要评论 JavaScript,请使用:

// single-line comment
// which needs to have the double-slash
// preface each comment-line...

或者:

/* This is a multi-line
   comment, and this text
   will happily remain commented-out
   until you get to
   one of these comment-close things, just to the right -> */

引用文献:

关于Jquery move 表行但不 move 表头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7590070/

相关文章:

javascript - 我该怎么做才能让我的 cookie 同意横幅为每个用户 (ip) 弹出一次

javascript - 使用jQuery模拟下一个按钮点击

java - Struts:突出显示日历中的日期范围 (JQuery/Javascript)

javascript - 失去悬停后没有鼠标

c# - 对具有相同长度的大量字符串进行排序

c++ - 选择排序循环中的错误

c++ - 按代理排序(或 : sort one container by the contents of another) in C++

Python:将一个数据框的值添加到另一个数据框的某些行

c# - 无法从 xtragridview 获取点击行的数据

excel - 在 VBA Excel 中插入行