checkbox 實現單選效果(html)

note:在html <input> 標籤類中的checkbox實現單選效果。

在最近的開發項目中,客戶要求使用小方格子實現“單選”功能,顯然圓點的radio被out了,只能選擇chckbox的方塊樣式,也在網上搜過,可能有點兒腦殘,沒有找到。

廢話不多說直接上代碼:


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>checkbox實現單選效果</title>
    <script src="jquery-1.7.2.min.js"></script>
    <script>
        $(document).ready(function () {
            $('.sb').click(function () {
                var typeThis = typeof ($(this).attr("checked"));
                switch (typeThis) {
                    case "string":
                        if ($(this).attr("checked").toLowerCase()=="checked") {
                            $('.sb').each(function () {
                                $(this).removeAttr("checked");
                            });
                            $(this).attr("checked",true);
                        }
                        break;
                    case "undefined":
                        $('.sb').each(function () {
                            $(this).removeAttr("checked");
                        });
                        break;
                }
            });
        });
    </script>
</head>
<body>
    <input class="sb" type="checkbox" value="1"/>
    <input class="sb" type="checkbox" value="2" />
    <input class="sb" type="checkbox" value="3" />
    <input class="sb" type="checkbox" value="4" />
</body>
</html>

當然在case “undefined” 中的代碼可有可無,大家可以試試

ps:注意引用jQuery

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