我的表格行可以上下 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 > </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;
}
});
顺便说一句,您的脚本可能会从注释中生成错误(尽管我确实怀疑这些错误是为了我们的利益而添加的,而不是在您实际的 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 -> */
引用文献:
-
.prevAll()
. -
.nextAll()
. -
.length
.
关于Jquery move 表行但不 move 表头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7590070/