jQuery拖動排序並處理給後臺的數據

引入jquery和插件sortable.js(可在官網下載);

<script src="http://www.jq22.com/jquery/jquery-1.10.2.js"></script>
<script src="js/jquery-sortable.js"></script>

html結構

<h3>點擊下方拖拽排序</h3>

    <ol class='example'>
        
    </ol>

<button id="onList">獲取</button>

css

    <style>
        body.dragging,
        body.dragging * {
            cursor: move !important;
        }

        .dragged {
            position: absolute;
            opacity: 0.5;
            z-index: 2000;
        }

        ol.example li.placeholder {
            position: relative;
        }

        ol.example li.placeholder:before {
            position: absolute;
        }

    </style>

JS部分

思路:1存儲一份後臺數據

         2獲取拖拽過後的列表進行對比

         3獲取到哪些li順序發生改變。

    <script>
        $(function () {
            $("ol.example").sortable()
        })

        let arr = [{
            id: 1,
            cont: 1
        }, {
            id: 2,
            cont: 2
        }, {
            id: 3,
            cont: 3
        }, {
            id: 4,
            cont: 5
        }, {
            id: 6,
            cont: 6
        },]

        arr.forEach(item => {
            let str = `<li id="${item.id}" cont="${item.cont}">${item.cont}</li>`;

            $('.example').append(str)

        });


        let newArr = []
        $('#onList').click(function () {
            $('.example li').each(function (i) {
                newArr.push({
                    id: arr[i].id,
                    cont: $(this).attr('cont')
                })

            })

            let list = [];
            for (let j in newArr) {
                for (let i in arr) {

                    if (newArr[j].id == arr[i].id) {

                        if (newArr[j].cont != arr[i].cont) {
                            list.push({
                                id: newArr[j].id,
                                cont: newArr[j].cont
                            })
                        }

                    }
                }
            }

            console.log(list);
        })

    </script>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章