Javascript手动触发.onchange()事件 [英] Javascript manually firing .onchange() event

查看:442
本文介绍了Javascript手动触发.onchange()事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个输入字段,我想分配一个新值并触发.onchange()事件。我做了以下事情:

I have an input field I want to assign a new value and fire an .onchange() event. I did the following:

document.getElementById("range").value='500';
document.getElementById("range").onchange();

其中range是我的输入ID。
我收到以下错误:

Where range is my input Id. I get the following error:

Uncaught TypeError: Cannot read property 'target' of undefined

有没有办法定义'目标'?
谢谢

Is there a way to define the 'target'? Thank you

推荐答案

关于目标的错误是因为事件处理程序中的代码试图读取与change事件关联的 Event 对象的 target 属性。您可以尝试传入一个虚假事件来欺骗它:

The error about target is because there's code in the event handler that's trying to read the target property of the Event object associated with the change event. You could try passing in an faux-Event to fool it:

var range= document.getElementById('range');
range.onchange({target: range});

或者,如果可以的话,更改处理程序代码以使用 this 而不是 event.target 。除非您正在使用委托(从父级捕获子对象的更改事件,对于更改事件很麻烦,因为IE不会冒泡它们),更改事件的目标始终是事件处理程序的元素已注册,使 event.target 多余。

or, if you can, change the handler code to use this instead of event.target. Unless you are using delegation (catching change events on child object from a parent, something that is troublesome for change events because IE doesn't ‘bubble’ them), the target of the change event is always going to be the element the event handler was registered on, making event.target redundant.

如果事件处理程序使用<$ c $的更多属性c>事件而不仅仅是目标你需要假装更多,或者去真正的浏览器界面来调度事件。如果事件监听器可能正在使用(IE中的 addEventListener attachEvent ),那么这也是必要的。在直接 onchange 属性上可见。这是依赖于浏览器的(IE的 fireEvent ,标准的 dispatchEvent ),在较旧或更模糊的浏览器上不可用。

If the event handler uses more properties of Event than just target you would need to fake more, or go for the ‘real’ browser interface to dispatching events. This will also be necessary if event listeners might be in use (addEventListener, or attachEvent in IE) as they won't be visible on the direct onchange property. This is browser-dependent (fireEvent for IE, dispatchEvent for standards) and not available on older or more obscure browsers.

这篇关于Javascript手动触发.onchange()事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆