1. 程式人生 > >JQuery中的multipleselect選擇框

JQuery中的multipleselect選擇框

需求:選擇課程

程式碼實現:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="script/jquery-3.3.1.min.js"></script>
    <script>
        $(function () {
            //全部向右移動的事件
            $('#btnRightAll').click(function () {
               //獲取所有左側列表框所有子元素,並且將所有子元素新增到右列表框
                $('#selectLeft').children().appendTo('#selectRight');
            });
            //全部向左移動的事件
            $('#btnLeftAll').click(function () {
                //獲取所有左側列表框所有子元素,並且將所有子元素新增到右列表框
                $('#selectRight').children().appendTo('#selectLeft');
                //第二種寫法:獲取右側所有的option
                //$('#selectLeft').append($('#selectRight option'));
            });
            //“選中右移”按鈕繫結事件
            $('#btnRight').click(function () {
                //獲取到所有被選中的option
                //#selectLeft後面是有一個空格的,Select後面其實存在option,可以用空格代替
                $('#selectLeft :selected').appendTo('#selectRight');
            });
            //“選中左移”按鈕繫結事件
            $('#btnLeft').click(function () {
                //獲取到所有被選中的option
                //#selectRight後面是有一個空格的Select後面其實存在option,可以用空格代替
                 $('#selectRight :selected').appendTo('#selectLeft');
                //獲取右側選中的項,加到左邊
                //$('#selectLeft').append($('#selectRight :selected'));
            });
        });
    </script>
</head>
<body>
    <select id="selectLeft" multiple="true">
        <option>語文</option>
        <option>數學</option>
        <option>自然</option>      
    </select>
    <input type="button" id="btnRightAll" value=">>" />
    <input type="button" id="btnRight" value=">" />
    <input type="button" id="btnLeftAll" value="<<" />
    <input type="button" id="btnLeft" value="<" />
    <select id="selectRight" multiple="true"> </select>
</body>
</html>

效果展示:

未完,待續!