如何检测输入动态变化时的变化

How to detect the change on input when it changed dynamically

本文关键字:变化 动态 输入 何检测 检测      更新时间:2023-09-26

如何检测输入值动态变化时的变化。随着txt2上的更改,清除txt1中的值。我需要检测它是否已清除或更改。

Onchange不这样做。

<input id="txt1" type="text" onchange="SetDefault();" onpaste="this.onchange();" oninput="this.onchange();">
<br>

<input id="txt2" type="text" onchange="SetDefaultSecond();" onkeyup="this.onchange();" onpaste="this.onchange();" oninput="this.onchange();">
<script>
function SetDefault(){
      alert("Change1");
    }
function SetDefaultSecond(){
      $("#txt1").val('');
       alert("Change2");
}
</script>

您可以在清除第一个输入时手动触发输入事件,如下所示:

<input id="txt1" type="text">
<br>
<input id="txt2" type="text">
<script>
$("#txt1").on("input", function() {
    alert("Change1");
});
$("#txt2").on("input", function() {
    $("#txt1").val('').trigger('input');
    alert("Change2");
});
</script>

jsFiddle here: https://jsfiddle.net/dr0oabj1/

您需要使用oninput事件来捕获对输入的任何更改。onchange &oninput是onchange仅在焦点离开输入后触发,而作为oninput触发每次值由于任何原因而改变。

function SetDefault(){
      alert("Change1");
    }
function SetDefaultSecond(){
      $("#txt1").val('');
       alert("Change2");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input id="txt1" type="text" oninput="SetDefault();" />
<br>
<input id="txt2" type="text" oninput="SetDefaultSecond();"/>

试试这个:

$(document).ready(function(){
    $("#txt2").on("input",function(){
        $("#txt1").val('');
        console.log("Change2");
    })
    $("#txt1").on("input",function(){
        console.log("Change1");

    })
})

最终代码:

<!DOCTYPE html>
<html lang="en">
<head>
</head>
    
    <body>
        
        Text 1 : <input id="txt1" type="text">
        <br><br>
        Text 2 : <input id="txt2" type="text">
        
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
        <script>
        $(document).ready(function(){
            $("#txt2").on("input",function(){
                $("#txt1").val('');
                console.log("Change2");
            })
            $("#txt1").on("input",function(){
                console.log("Change1");
            })
        })
    </script>
    </body>
</html>

Kodies的答案是正确的;只需尝试这个超级简单的例子,然后继续使用JQuery

检测对a的所有更改(立即)

<input id="txt1" type="text" oninput="console.log('input')" onchange="this.oninput()">
<br>
<button onclick="eval(this.textContent)">console.log('clearing'); txt1.value=''</button>
<br>
<button onclick="eval(this.textContent)">console.log('clearing <b>and triggering</b>'); txt1.value=''; <b>txt1.onchange()</b></button>

在txt2中使用

 oninput="changeClass(txt2);"    

和in script

function changeClass(text) {
    if(text.value==''){
        //code for clear txt1
    }
}