完成foo()函数的内容,要求能够弹出对话框提示当前选中的是第几个单选框。

完成foo()函数的内容,要求能够弹出对话框提示当前选中的是第几个单选框。

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <form name="form1">
        <input type="radio" name="radioGroup" />
        <input type="radio" name="radioGroup" />
        <input type="radio" name="radioGroup" />
        <input type="radio" name="radioGroup" />
        <input type="radio" name="radioGroup" />
        <input type="radio" name="radioGroup" />
        <input type="submit" />
    </form>
    <script>
        //非闭包
        var Inputs = document.getElementsByTagName('input')
        for(let i =0 ;i<Inputs.length;i++){
                Inputs[i].onclick=function(e){
            var  target = e.target || e.srcElement
                    for (let i = 0; i < Inputs.length; ++i) {
                    if (target.type=="radio" && target == Inputs[i]) {
                        alert(++i);
                        break;
                    }
                }
                    console.log(target)
                }
        }
        //闭包方法
        // var foo = (function () {
        //     var radio_list = (function () {
        //         var _list = [],
        //             nodes = document.getElementsByTagName('input');
        //             console.log(nodes.length)
        //         for (var i = 0; i < nodes.length; ++i) {
        //             var node = nodes[i];
        //             if (node.type == 'radio' && node.name == 'radioGroup') {
        //                 if (node.attachEvent)
        //                     node.attachEvent('onclick', function (e) { foo(e) });
        //                 else if (node.addEventListener)
        //                     node.addEventListener('click', function (e) { foo(e) }, false);
        //                 _list.push(node);
        //             }
        //         }
        //         return _list;
        //     })();
        //     return function (e) {
        //         var o = (function () {
        //             if (e) return e.target || e.srcElement;
        //             else if (window.event) return e.srcElement;
        //         })();
        //         for (var i = 0; i < radio_list.length; ++i) {
        //             if (o == radio_list[i]) {
        //                 alert(++i);
        //                 break;
        //             }
        //         }
        //     }
        // })();
    </script>
</body>

</html>
posted @ 2020-08-20 14:12  Cupid05  阅读(14)  评论(0编辑  收藏  举报