jQuery与原生JS监听Input输入框值变化的方法对比

作者:微光

时间:2026-10-23

浏览:412

本文详解如何在HTML中监听input输入框的值变化。对比原生onchange(失焦触发)与oninput(实时触发)的差异,并介绍jQuery中通过绑定input和propertychange事件实现跨浏览器兼容监听的方法,涵盖代码示例与注意事项。

文章目录

在Web开发中,实时获取用户输入内容通常涉及监听input元素的事件。

onchange事件特性

onchange事件机制:

该事件仅在input元素失去焦点时触发。

在输入过程中,内容发生变化不会立即触发该事件,必须当鼠标点击其他位置使输入框失焦后才会执行。

onchange事件在所有主流现代浏览器中均得到支持。

此属性适用于<input>、<select>以及<textarea>等表单元素。


<script>
  function change(){
    var x=document.getElementById("password");
    x.value=x.value.toUpperCase();<br data-filtered="filtered">    console.log("出发了")
   }
</script>
</head>
<body>
 
  输入你的密码: <input type="text" id="password" onchange="change()">
 
</body>

oninput事件特性

oninput事件机制:

当用户进行输入操作时触发,只要元素值发生改变,该事件便会立即执行。

该事件专门针对<input>或<textarea>元素,在值发生变动时触发。

需要注意的是,通过脚本修改值或从浏览器下拉提示框中选择值时,不会触发此事件。此外,IE9以下版本不支持该事件,在这些旧版浏览器中需使用onpropertychange事件作为替代方案。


JS: <input type="text" id="password" oninput="change()">

jQuery: $("#password").on('input propertychange', change);

onpropertychange兼容方案

onpropertychange事件机制:

该事件会实时触发,当元素的属性发生改变时即响应。但需注意,当元素被设置为disable=true时,该事件不会触发。

其主要缺陷在于仅IE浏览器支持,其他现代浏览器不支持,因此通常结合oninput事件来解决兼容性问题。


<input type="text" id="password" oninput="onpropertychange()">

jQuery与JS实现代码

使用jQuery进行监听:


<!DOCTYPE html> 
<html> 
  <head> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
    <title>RunJS</title> 
  <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
  </head> 
  <body> 
    <input type="text" id="password" autoComplete='off'> 
   <script type="text/javascript">
$(function(){ 
  $('#password').bind('input propertychange', function() { <br data-filtered="filtered">     console.log('在实时触发!!!')
    $('#result').html($(this).val().length); <br data-filtered="filtered">     $(this).val().length != 0 ? $("#login").css("background-color", "#086AC1") : $("#login").css("background-color", "#529DE0")
  });
})  
    </script>
  </body> 
</html>  

原生JavaScript实现:


<script type="text/javascript">
  // Firefox, Google Chrome, Opera, Safari, Internet Explorer from version 9
    function OnInput (event) {
      alert ("The new content: " + event.target.value);
    }
  // Internet Explorer
    function OnPropChanged (event) {
      if (event.propertyName.toLowerCase () == "value") {
        alert ("The new content: " + event.srcElement.value);
      }
    }
</script>
 
<input type="text" oninput="OnInput (event)" onpropertychange="OnPropChanged (event)" value="Text field" />

以上介绍了监听input值变化的核心知识点,包括各事件的触发时机、适用范围及兼容性处理方案。

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章