问题
I am using jQuery sortable to sort my table. see my structure
<table id="sortable">
<tr class="not">
<td>Elements</td>
</tr>
<tr>
<td>I am first</td>
</tr>
<tr>
<td>I am second</td>
</tr>
<tr>
<td>I am third</td>
</tr>
</table>
my jquery is
<script>
jQuery('#sortable tbody').sortable({
update: function (event, ui) { },
cancel: '.not',
});
</script>
Here I can move the
<tr>
<td>I am first</td>
</tr>
<tr>
<td>I am second</td>
</tr>
<tr>
<td>I am third</td>
</tr>
rows to before
<tr class="not"><td>Elements</td></tr>
How can I block that movement ?
回答1:
If you want to block only the first element, if it is a heading of the table put a <thead>
tag
see example
<table id="sortable">
<thead>
<tr class="not"><td>Elements</td></tr>
</thead>
<tbody>
<tr><td>I am first</td></tr>
<tr><td>I am second</td></tr>
<tr><td>I am third</td></tr>
</tbody>
</table>
<script>
jQuery('#sortable tbody').sortable({
update: function (event, ui) { }
});
</script>
See demo :http://jsfiddle.net/arunkumarthekkoot/7hhza/
回答2:
You can try comparing the offset.top
value of .not
and sortable
element in the sort or stop
function. Based on the result of comparison, you can cancel/allow the sort:
JS Code:
jQuery('#sortable tbody').sortable({
update: function (event, ui) {},
cancel: '.not',
stop: function (event, ui) {
var p = $('.not').offset().top;
var P = ui.position.top;
if (P < p) {
return false;
}
}
});
HTML:
<table id="sortable">
<tr>
<td>Elements</td>
</tr>
<tr>
<td>I am first</td>
</tr>
<tr class="not">
<td>I am second</td>
</tr>
<tr>
<td>I am third</td>
</tr>
</table>
Demo: http://jsfiddle.net/lotusgodkk/GCu2D/155/
回答3:
You can use item option to exclude specific items. like this:
jQuery('#sortable tbody').sortable({
items: 'tr:not(.not)'
});
来源:https://stackoverflow.com/questions/23865324/how-to-block-movement-of-tr-in-jquery-sortable