多个AddEventListener表单提交

时间:2018-05-02 03:58:45

标签: javascript html forms dom web

我尝试建立一个倒数计时器,它有3个控制计时器的按钮。 3个按钮启动,取消和暂停。计时器只是文本输入字段,您可以在其中输入正整数。

我必须使用核心JavaScript,而不是jQuery

开始按钮:开始倒计时到0

取消按钮:重新显示默认输入值

暂停按钮:将定时器保持在当前值,直到单击“开始”按钮,然后恢复正常操作。

我对这3个提交按钮使用addEventListener方法,但是当我点击任意按钮时,它们同时触发了所有按钮。我试图放置e.preventDefault和e.stopImmediatePropagation,但它并没有真正的帮助。



<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Countdown</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
        ul {
            list-style-type: none;
            background-color: #03f72c;
        }

        .invalid {
            background-color: #c71f1f;
        }
    </style>
</head>

<body>
    <div>
        <h1>Countdown</h1>
        <form id="myForm">
            <div>
                <label for="posint">Timer:</label>
                <input type="text" id="input" name="posint">
            </div>
            <div class="controller">
                <div class="button">
                    <input id="start" type="submit" value="Start"></input>
                </div>
                <div class="button">
                    <input id="pause" type="submit" value="Pause"></input>
                </div>
                <div class="button">
                    <input id="cancel" type="submit" value="Cancel"></input>
                </div>
            </div>
            <div id="errormsgs">
                <ul id="warning">
                    <h3>Checklist</h3>
                    <li id="posint_err"></li>
                </ul>
            </div>
        </form>
    </div>
    <script>
        function formControl() {
            // getting input value
            var input = document.getElementById("input");
            var myForm = document.getElementById("myForm");
            myForm.addEventListener("submit", start);
            myForm.addEventListener("submit", cancel);
            myForm.addEventListener("submit", pause);
            // regex validate
            var containInt = /^-?[0-9]\d*$/;
            // ======== UI text ========
            var posint_err = "It must contain only an integer greater than 0";
            var expiredMsg = "expired";

            function render(target, content, attributes) {
                for (const key in attributes) {
                    target.setAttribute(key, attributes[key]);
                }
                target.value = content;
            }
            // Select All function
            function selectAll() {
                input.focus();
                input.setSelectionRange(0, input.value.length);
            }
            // UI state
            const state = {
                defaultValue: "",
                failed() {
                    document.getElementById("warning").classList.add("invalid");
                    document.getElementById("posint_err").innerHTML = posint_err;
                    document.getElementById("posint_err").style.display = "block";
                },
                success() {
                    document.getElementById("errormsgs").style.display = "none";
                },
                clear() {
                    document.getElementById("posint_err").style.display = "none";
                },
            }
            // start function
            function start(e) {
                if (parseInt(input.value) <= 0 || (!(input.value.match(containInt)))) {
                    state.clear()
                    state.failed();
                    selectAll();
                    e.preventDefault();
                    e.stopImmediatePropagation();
                    return false
                } else {
                    // success case
                    var inputValue = parseInt(input.value);
                    state.defaultValue = inputValue;
                    e.preventDefault();
                    e.stopImmediatePropagation();
                    state.success();
                    input = setInterval(countdown, 1000);
                    // Countdown function()
                    function countdown() {
                        inputValue--;
                        render(document.getElementById("input"), inputValue)
                        if (inputValue <= 0) {
                            clearInterval(input);
                            render(document.getElementById("input"), expiredMsg)
                        }
                    }
                    return false
                }
            }
            // cancel function
            function cancel(e) {
                // e.stopImmediatePropagation();
                // console.log(state.defaultValue)
                e.preventDefault();
                e.stopImmediatePropagation();
                clearInterval(input);
                render(input, state.defaultValue);
                return false
            }
            // cancel function
            function pause(e) {
                e.preventDefault();
                e.stopImmediatePropagation();
                console.log('pause')
                return false
            }
        }
        window.onload = function () {
            formControl();
        };
    </script>
</body>

</html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

请勿将听众附加到form - 请将其附加到input。 (另外,从这些输入中删除type="submit" - 改为使用type="button",以显示您想要的方式)

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Countdown</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
        ul {
            list-style-type: none;
            background-color: #03f72c;
        }

        .invalid {
            background-color: #c71f1f;
        }
    </style>
</head>

<body>
    <div>
        <h1>Countdown</h1>
        <form id="myForm">
            <div>
                <label for="posint">Timer:</label>
                <input type="text" id="input" name="posint">
            </div>
            <div class="controller">
                <div class="button">
                    <input type="button" id="start" value="Start"></input>
                </div>
                <div class="button">
                    <input type="button" id="pause" value="Pause"></input>
                </div>
                <div class="button">
                    <input type="button" id="cancel" value="Cancel"></input>
                </div>
            </div>
            <div id="errormsgs">
                <ul id="warning">
                    <h3>Checklist</h3>
                    <li id="posint_err"></li>
                </ul>
            </div>
        </form>
    </div>
    <script>
        function formControl() {
            // getting input value
            var input = document.getElementById("input");
            var myForm = document.getElementById("myForm");
            document.querySelector('#start').addEventListener("click", start);
            document.querySelector('#cancel').addEventListener("click", cancel);
            document.querySelector('#pause').addEventListener("click", pause);
            // regex validate
            var containInt = /^-?[0-9]\d*$/;
            // ======== UI text ========
            var posint_err = "It must contain only an integer greater than 0";
            var expiredMsg = "expired";

            function render(target, content, attributes) {
                for (const key in attributes) {
                    target.setAttribute(key, attributes[key]);
                }
                target.value = content;
            }
            // Select All function
            function selectAll() {
                input.focus();
                input.setSelectionRange(0, input.value.length);
            }
            // UI state
            const state = {
                defaultValue: "",
                failed() {
                    document.getElementById("warning").classList.add("invalid");
                    document.getElementById("posint_err").innerHTML = posint_err;
                    document.getElementById("posint_err").style.display = "block";
                },
                success() {
                    document.getElementById("errormsgs").style.display = "none";
                },
                clear() {
                    document.getElementById("posint_err").style.display = "none";
                },
            }
            // start function
            function start(e) {
                if (parseInt(input.value) <= 0 || (!(input.value.match(containInt)))) {
                    state.clear()
                    state.failed();
                    selectAll();
                    e.preventDefault();
                    e.stopImmediatePropagation();
                    return false
                } else {
                    // success case
                    var inputValue = parseInt(input.value);
                    state.defaultValue = inputValue;
                    e.preventDefault();
                    e.stopImmediatePropagation();
                    state.success();
                    input = setInterval(countdown, 1000);
                    // Countdown function()
                    function countdown() {
                        inputValue--;
                        render(document.getElementById("input"), inputValue)
                        if (inputValue <= 0) {
                            clearInterval(input);
                            render(document.getElementById("input"), expiredMsg)
                        }
                    }
                    return false
                }
            }
            // cancel function
            function cancel(e) {
              console.log('cancel');
                // e.stopImmediatePropagation();
                // console.log(state.defaultValue)
                e.preventDefault();
                e.stopImmediatePropagation();
                clearInterval(input);
                render(input, state.defaultValue);
                return false
            }
            // cancel function
            function pause(e) {
                e.preventDefault();
                e.stopImmediatePropagation();
                console.log('pause')
                return false
            }
        }
        window.onload = function () {
            formControl();
        };
    </script>
</body>

</html>