Input 자동 보완 및 입력한 데이터를 로컬에 저장

3282 단어
<!-- lang: js -->
    <!DOCTYPE HTML PUBLIC
        "-//W3C//DTD HTML 4.01//EN"
        "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head lang="en">
        <meta charset="UTF-8">
        <script src="jquery.js"></script>
        <script src="../bower_components/jquery-ui/jquery-ui.min.js"></script>
        <script src="../bower_components/store.js/store.js"></script>
        <link rel="stylesheet" href="../bower_components/jquery-ui/themes/ui-lightness/jquery-ui.min.css"/>
        <link rel="stylesheet" href="jquery.ui.autocomplete.css"/>
        <script>
            $(function () {
                //todo:id should be an array

                function inputSave(inputTextId, storeId, num) {
                    var ele = $('#' + inputTextId);
                    if (ele[0].tagName != "INPUT") {
                        return;
                    }
                    var inputValue = $.trim(ele.val());
                    if (inputValue) {
                        storeInput(inputValue, storeId, num);
                    }
                }

                function storeInput(inputValue, storeId, num) {
                    var inputStr = localStorage.getItem(storeId);
                    var inputArr = inputStr ? inputStr.split(',') : new Array();
                    var idx = $.inArray(inputValue, inputArr);
                    if (idx != -1) {
                        inputArr.splice(idx, 1);
                    }
                    inputArr.unshift(inputValue);
                    if (inputArr.length > num) {
                        inputArr.pop();
                    }
                    localStorage.setItem(storeId, inputArr);
                }

                function autoComplete(inputTextId, storeId, num) {
                    inputSave(inputTextId, storeId, num);
                    var source = localStorage.getItem(storeId);
                    $('#' + inputTextId).autocomplete({source: source.split(',')});
                }

                $('#saveBtn').click(function () {

                    autoComplete("jack", "jack", 10);
                });
                $('#clearBtn').click(function () {
                    localStorage.removeItem("jack");
                    localStorage.removeItem("zen");
                    console.log('clear data ok!');

        });
    </script>
    <title></title>
</head>
<body>
<div class="ui-widget">
    <input type="text" id="jack" placeholder="this is test"/>
    <input type="text" id="zen" placeholder="this is test"/>
    <label for="tags">Tags: </label>
    <input id="tags">
    <button id="saveBtn" class="ui-button-text-icons">Save Input Data to Local</button>
    <button id="clearBtn" class="ui-button-text-icons">Clear localData</button>
</div>
</body>
</html>

좋은 웹페이지 즐겨찾기