How to block movement of tr in jquery sortable?

放肆的年华 提交于 2019-12-13 02:51:56

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!