老项目中如何监听js改变input的value值事件

578 阅读1分钟

老项目中如何监听js改变input的value值事件

目前写的项目多数为Vue,监听值变更的方法也多了起来,如Watch等。。。

但是在面对传统项目的时候(Jquery)等项目的时候。就无法监听到js改变input的val值的事件了。

最后发现一种解决方案:可以通过自定义事件来曲线救国,代码示例如下:

<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Document</title>
</head>

<body>
	id是input<input id="input">
	id是input1<input id="input1">
</body>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
<script>
	/**
	 * @parmas String input框的id
	 * @parmas String 值变更需要执行的函数名称
	 * @parmas Function 值变更需要执行的函数体
	 * describe js改变input的value触发一个自定义事件
	 */
	function jsValChange(inputId, funName, fun) {
		const props = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value');
		let oldVal = '',
			newVal = '';
		Object.defineProperty(HTMLInputElement.prototype, 'value', {
			...props,
			set(v) {
				oldVal = this.value;
				newVal = v;
				props.set.call(this, v);
				if (oldVal !== v && this.id === inputId) {
					document.getElementById(inputId).dispatchEvent(new CustomEvent(funName, {
						detail: {
							newVal,
							oldVal
						}
					}));
				}
			}
		});

		document.getElementById(inputId).addEventListener(funName, fun);
	}


	//使用方法
	//1.定义一个值变更需要执行的函数
	//2.调用jsValChange函数传三个参数
	function inputChange(e) {
		console.log('值发生了变化', e.detail);
	}

	jsValChange('input1', "inputChange", inputChange)
</script>

</html>

测试结果如下:

可见当改变id为input1的值,触发了我们定义的inputChange

12312.jpg