DOM input 事件 值发生变化时触发

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hsl0530hsl/article/details/88315482

input事件当<input>、<select>、<textarea>的值发生变化时触发。对于复选框(<input type=checkbox>)或单选框(<input type=radio>),用户改变选项时,也会触发这个事件。另外,对于打开contenteditable属性的元素,只要值发生变化,也会触发input事件。

input事件的一个特点,就是会连续触发,比如用户每按下一次按键,就会触发一次input事件。

input事件对象继承了InputEvent接口。

该事件跟change事件很像,不同之处在于input事件在元素的值发生变化后立即发生,而change在元素失去焦点时发生,而内容此时可能已经变化多次。也就是说,如果有连续变化,input事件会触发多次,而change事件只在失去焦点时触发一次。

下面是例子。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Dom Input Event</title>
</head>
<body>
    <label>Text: <input type="text" id="text"/></label>
    <br>
    //label[for='sel']{'Select:'}+select#sel[name='sel']>option[value=$]{$}*5
    <label for="sel">Select:</label>
    <select name="sel" id="sel">
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
        <option value="5">5</option>
    </select>
    <br>
    //(label[for='r'$]{r$}+input#r$[type='radio'][name='radio'][value='r'$])*5
    <label for="r1">r1</label><input type="radio" name="radio" value="r1" id="r1">
    <label for="r2">r2</label><input type="radio" name="radio" value="r2" id="r2">
    <label for="r3">r3</label><input type="radio" name="radio" value="r3" id="r3">
    <label for="r4">r4</label><input type="radio" name="radio" value="r4" id="r4">
    <label for="r5">r5</label><input type="radio" name="radio" value="r5" id="r5">
    <br>
    <label for="tta">'TextArea:'</label>
    <textarea name="tta" id="tta" cols="30" rows="10"></textarea>
<script>
    var text = document.querySelector("#text");
    text.addEventListener("input", function (e) {
        console.log(e.target.value);
    });

    var select = document.querySelector("#sel");
    select.addEventListener("input", function (e) {
        console.log(e.target.value);
    });
    var radio = document.getElementsByName("radio");//.querySelectorAll("input[name='radio']");

    for (var i = 0; i < radio.length; i++) {
        radio[i].addEventListener("input", function (e) {
            console.log(e.target.value);
        });
    }

    var tta = document.querySelector("#tta");
    tta.addEventListener("input", function (e) {
        console.log(e.target.value);
    });
</script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/hsl0530hsl/article/details/88315482