JavaScript 中检测 input 改变的方法通常有以下几种:
<input>
元素的值发生变化时触发。<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Input Change Detection</title>
</head>
<body>
<input type="text" id="myInput">
<script>
// 获取 input 元素
var inputElement = document.getElementById('myInput');
// 添加 input 事件监听器
inputElement.addEventListener('input', function(event) {
console.log('Input value changed to:', event.target.value);
});
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Input Change Detection with jQuery</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<input type="text" id="myInput">
<script>
$(document).ready(function(){
$('#myInput').on('input', function() {
console.log('Input value changed to:', $(this).val());
});
});
</script>
</body>
</html>
function debounce(func, wait) {
let timeout;
return function(...args) {
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, args), wait);
};
}
const debouncedHandler = debounce(function(event) {
console.log('Input value changed to:', event.target.value);
}, 300);
inputElement.addEventListener('input', debouncedHandler);
通过上述方法,可以有效检测 input 元素的改变,并根据需要进行相应的处理。
领取专属 10元无门槛券
手把手带您无忧上云