描述

change事件触发规则

输入框,单选,下拉框的值发生改变后失去焦点时触发

用代码来修改值不会触发

解决

jq调用触发

$(target).trigger('change')

代码

<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    <title>Document</title>
    <style>
        label,
        select {
            display: inline-block;
            line-height: 30px;
        }

        label {
            padding-left: 20px;
            width: 200px;
        }

        select {
            width: 200px;
        }

        #div_b,
        #div_c {
            display: none;
        }
    </style>
</head>

<body>
    <h3>change事件触发规则</h3>
    <h4>输入框、单选、下拉框的值发生改变后失去焦点时触发</h4>
    <h4>用代码来修改值不会触发</h4>


    <form>
        <div id="div_a">
            <label for="form_a">A</label>
            <input type="text" id="form_a" placeholder="1/2">
        </div>
        <div id="div_b">
            <label for="form_b">B:show when A is 2</label>
            <input type="text" id="form_b" placeholder="1/2">
        </div>
        <div id="div_c">
            <label for="form_c">C:show when B is 2</label>
            <input type="text" id="form_c" placeholder="1/2">
        </div>
    </form>

    <script>
        $(document).ready(() => {
            bindChange()
        })
        function bindChange() {
            $('#form_a').bind('change', function () {
                let value = $(this).val()
                value === '2' ? $('#div_b').show() : hideAndReset('#div_b', '#form_b')
            })
            $('#form_b').bind('change', function () {
                let value = $(this).val()
                value === '2' ? $('#div_c').show() : hideAndReset('#div_c', '#form_c')
            })
        }

        function hideAndReset(hideId, resetID) {
            $(hideId).hide()
            $(resetID).val('').trigger('change')
        }

    </script>
</body>

</html>