如何模拟单击或按键事件?
我需要模拟单击或鼠标事件。我尝试了各种方法,但我使用的库似乎没有响应,或者确实响应,但仅在特定浏览器上响应。我做 ATM $('#target').val($('#target2').val());适用于 Firefox 和 Opera。在 chrome、IE8 和 safari 上失败。
我可以将事件添加到库中,但我不知道要添加哪个事件(或如何正确执行)。无论如何,我该如何解决这个问题?基本上我用 .val() 设置文本区域文本,而库似乎没有接收到该事件。
I need to simulate a click or mouse event. I tried various things but the lib i am using doesnt seem to respond to it or does respond but only on specific browsers. ATM i do $('#target').val($('#target2').val()); which works on firefox and opera. Fails on chrome, IE8 and safari.
I could add events to the libs but i wouldnt know which event to add (or how to do it properly). Anyways how do i solve this? basically i am setting the textarea text with .val() and the lib doesnt seem to pick up that event.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 DOM Level 2 事件模型,例如:
演示: http://www.jsfiddle.net/ 4yUqL/66/
这将真正模拟元素上的鼠标单击。不管事件如何绑定。
You could use the DOM Level 2 Event Model, like:
Demo: http://www.jsfiddle.net/4yUqL/66/
This will truly simulate a mouseclick on an element. Regardless how events were bound.
jQuery 中的
.trigger('click')
可能会实现您的目标试图做。它将触发附加到单击事件的所有处理程序。.trigger('click')
in jQuery might achieve what you're trying to do. It will fire all the handlers attached to the click event.如果有人遇到这个问题,正在寻找一种与框架无关的方式来触发任何 HTML 和鼠标事件,请查看此处:如何使用 JavaScript 模拟鼠标点击?
In case anyone bumps into this looking for a framework agnostic way to fire any HTML and Mouse event, have a look here: How to simulate a mouse click using JavaScript?