Onchange事件不能正常运行 [英] Onchange event is not working well
问题描述
我创建了以下html页面。
< html>
< head>< / head>
< body>
< input type =textvalue =id =Textboxonchange =alert('text change'); />
< input type =buttonvalue =onclick =document.getElementById('Textbox')。value ='Hello'; />
< / body>
< / html>
当输入的文本输入到文本框时,onchange事件正常工作。我写了一个代码,当按钮被点击时,Hello文本被输入到文本框中。但是文本框的onchange事件不能正常工作。如何捕捉更改事件?谢谢。
以编程方式更改值不会触发更改事件,只有当用户聚焦元素时,才会发生变化,然后将焦点放在其他位置。 p>
选项是手动调用onchange监听器,在该元素上发布更改事件,或者通过上传DOM查找具有onchange监听器的父母并调用它们来手动启动更改事件。
这是一个似乎符合账单的答案:手动触发onchange事件
某些链接:
- MDN dispatchEvent(符合标准): https://developer.mozilla.org/en/DOM/element.dispatchEvent
- MSDN fireEvent(IE专有): http://msdn.microsoft.com/en-us/library/ie/ms536423(v = vs85).aspx
I created a following html page.
<html>
<head></head>
<body>
<input type="text" value="" id="Textbox" onchange="alert('text change');" />
<input type="button" value="" onclick="document.getElementById('Textbox').value = 'Hello';" />
</body>
</html>
When the entered text is inputted into the textbox, the onchange event is working well. I wrote a code that when the button is clicked, the 'Hello' text is inputted into the the textbox. But the onchange event of the textbox is not working well. How can I catch change event? Thanks.
Programmatically changing the value doesn't fire a change event, that only occurs if the user focuses the element, changes the value and then puts focus elsewhere.
Options are to manually call the onchange listener, dispatch a change event on the element, or manually bubble the change event by going up the DOM looking for parents with an onchange listener and calling them.
Here is an answer that seems to fit the bill: trigger onchange event manually
Some links:
- MDN dispatchEvent (standards compliant): https://developer.mozilla.org/en/DOM/element.dispatchEvent
- MSDN fireEvent (IE proprietary): http://msdn.microsoft.com/en-us/library/ie/ms536423(v=vs.85).aspx
这篇关于Onchange事件不能正常运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!