当以编程方式更改输入时,on change 的解决方案不起作用

我已经阅读了为什么 onchange 不起作用?现在我知道了,

onchange 事件仅在用户更改输入值时触发。如果以编程方式更改输入,则不应触发

但是我有一个输入字段,当用户通过网站内的 Google 地图小部件更改位置时,该字段会自动填充。当它发生时,我想获得自动填充的值并填充另一个输入字段。以编程方式更改输入时,如何检测或触发功能?


喵喔喔
浏览 234回答 3
3回答

SMILET

您可以通过覆盖输入value属性的 setter 函数来实现这一点。因此,每次有人以value编程方式设置时,您的覆盖设置器都会被触发:const input = document.getElementById('input');const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(input), 'value');Object.defineProperty(input, 'value', {&nbsp; &nbsp; set: function(t) {&nbsp; &nbsp; &nbsp; &nbsp; console.log('Input value was changed programmatically');&nbsp; &nbsp; &nbsp; &nbsp; return descriptor.set.apply(this, arguments);&nbsp; &nbsp; },&nbsp; &nbsp; get: function() {&nbsp; &nbsp; &nbsp; return descriptor.get.apply(this);&nbsp; &nbsp; }});function changeInput() {&nbsp; input.value += '1';}<input id="input"><button onclick="changeInput()">Change</button>

跃然一笑

要以编程方式触发事件,您可以使用事件 API:https : //developer.mozilla.org/fr/docs/Web/API/EventTarget/dispatchEvent完整示例:let input = document.getElementById('a')// Listen the eventinput.addEventListener('change', function (evt) {&nbsp; &nbsp;console.log('onchange event listener')});input.onchange = () => {console.log('onchange callback')}setTimeout(() => {input.value = "myvalue"// Trigger the eventvar event = new Event('change');input.dispatchEvent(event);}, 1000)<input id="a">

绝地无双

对于以编程方式更改输入标签中的值,您可以使用triggers.$(document).on('mytrigger keyup', '#input_num', function() {&nbsp; var value = $('#input_num').val();&nbsp; //alert(value);&nbsp; $('#result').val(value)})function external_modifier(){&nbsp; setTimeout(function(){&nbsp; &nbsp; var intValue = parseInt($('#input_num').val(), 10);&nbsp; &nbsp; $('#input_num').val(intValue+1).trigger("mytrigger");&nbsp; &nbsp; //alert(intValue);&nbsp; &nbsp; external_modifier();&nbsp; }, 3000);}external_modifier();<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><lable> Input: </lable><input id='input_num' type=text value=1 /><br><br><lable> Result: </lable><input id='result' type=text disabled />
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript