gpt4 book ai didi

javascript - document.dispatchEvent() 在 Firefox 中不起作用

转载 作者:太空狗 更新时间:2023-10-29 14:57:38 25 4
gpt4 key购买 nike

我遇到了 element.dispatchEvent(e); 在 Firefox 中无法正常工作的问题。

jsFiddle我遇到问题的例子。

element.dispatchEvent(e); 触发,并返回 true 但所需的事件/效果没有发生,在 fiddle 的情况下,a 的打开选择下拉菜单。

它在 Chrome(版本 43.0.2357.134 m)上运行良好。
我正在使用 Firefox 39.0 对此进行测试,不知道旧版本是否会出现这种情况,还是新版本才会出现这种情况。

任何指向正确方向的指示都将不胜感激。

最佳答案

这可能不是完整的答案,因为浏览器处理选择元素和事件的方式有很多差异,但部分问题可能归因于 isTrusted Event 的属性(property)目的。看这里: https://developer.mozilla.org/en-US/docs/Web/API/Event/isTrusted

您可以看到浏览器之间已经存在差异:

In Firefox, an event is trusted if it is invoked by the user and not
trusted if it is invoked by a script.

In Internet Explorer, all events are trusted except those that are
created with the createEvent() method.

Chrome does not support this property.

如果你看一下 isTrusted方法: http://www.w3.org/TR/2012/WD-DOM-Level-3-Events-20120614/#trusted-events

Events that are generated by the user agent, either as a result of user interaction, or as a direct result of changes to the DOM, are trusted by the user agent with privileges that are not afforded to events generated by script through the DocumentEvent.createEvent("Event") method, modified using the Event.initEvent() method, or dispatched via the EventTarget.dispatchEvent() method. The isTrusted attribute of trusted events has a value of true, while untrusted events have a isTrusted attribute value of false.

Most untrusted events should not trigger default actions, with the exception of click or DOMActivate events. These events trigger the default action of an activation trigger (see Activation triggers and behaviors for more details); these untrusted events have an isTrusted attribute value of false, but still initiate any default actions for backwards compatibility. All other untrusted events must behave as if the Event.preventDefault() method had been called on that event.

所以基本上,脚本生成的事件,至少在 Firefox 中,不一定表现得与用户生成的事件完全一样。您可以使用它来触发默认行为,例如选中复选框或点击链接,但在许多情况下,它不会执行与通过界面实际生成事件相同的操作。它会被解雇,但有限制。

同样,也许有一种方法可以实现您正在尝试的目标,我不完全确定这是导致此特定问题的原因,但从规范中可以清楚地看出,不能保证通过脚本模拟用户交互去工作。

关于javascript - document.dispatchEvent() 在 Firefox 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31491549/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com