神奇的单项选择题和多项选择题答案js选项生成算法

选项答案可以用纯数字存储(其实这种也是很好处理选择答案的的方法),这就依靠js的选项生成算法了以及后台的选项生成算法

js选项生成算法(A~Z)

 function getCharStringByInteger(ind) {
            var ret = "";
            for (var i = 0; i < 26; i++) {
                var pow = Math.pow(2, i);
                if (pow > ind) {
                    break;
                }
                //console.log((ind & pow) + "w")
                //console.log(ind  + "i")
                //console.log(pow + "p")
                if ((ind & pow) > 0) {
                    if (ret.length == 0) {
                        ret += String.fromCharCode(65 + i);
                    } else {
                        ret += "、" + String.fromCharCode(65 + i);
                    }
                }
            }
            return ret;
        }

简单的单项选择题和多项选择题答案生成的HTML页面

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <div style="width:250px;margin:auto;margin-top:50px;">
        <input type="text" id="select-number" style="height:35px;width:250px;" />
        <a id="ok" style="width:250px;height:35px;display:block;margin-top:30px;text-align:center;background-color:#b6ff00;line-height:35px;">确定</a>
        <input type="text" id="return-number" style="height:35px;width:250px;margin-top:30px;" />
    </div>
    <script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>
    <script type="text/javascript">

        $("#ok").click(function () {
            $("#return-number").val(getCharStringByInteger($("#select-number").val()));
        });


        function getCharStringByInteger(ind) {
            var ret = "";
            for (var i = 0; i < 26; i++) {
                var pow = Math.pow(2, i);
                if (pow > ind) {
                    break;
                }
                //console.log((ind & pow) + "w")
                //console.log(ind  + "i")
                //console.log(pow + "p")
                if ((ind & pow) > 0) {
                    if (ret.length == 0) {
                        ret += String.fromCharCode(65 + i);
                    } else {
                        ret += "、" + String.fromCharCode(65 + i);
                    }
                }
            }
            return ret;
        }
    </script>
</body>
</html>

生成选项的样例



ps:(ind &  pow)> 0 中的&运算符在下一遍文章有详细的解析,后台的算法后面再写

后台选项生成算法






posted @ 2017-10-21 09:29  神将飞蓬  阅读(388)  评论(0编辑  收藏  举报