gpt4 book ai didi

javascript - 如何创建一个完美的假 jQuery 事件对象

转载 作者:行者123 更新时间:2023-12-01 00:59:56 25 4
gpt4 key购买 nike

我正在对网站进行自动化测试,但有些事件我无法在 - 特别是但不限于 - IE 中使用 javascript 正确触发。 (我正在使用 selenium,但其他所有选项都不起作用,所以 javascript 是我最后的希望)

事件的函数似乎使用了 jquery Event 对象中的很多字段,我尝试按照 official jquery documentation 进行操作。但是,虽然它显示了大多数字段名称,但它没有显示如何填充它们(因为这不是您通常使用它所做的事情,但在我的情况下是这样)

我的问题如下:

为了伪造鼠标事件我该如何填充事件对象的字段(如何使用jQuery.Event("event type ",{param1:value1,param2:value2,...}) (或其他方法,如果有更有效的方法)

此事件对象与 element.trigger('eventname',EventObject)

一起使用

最佳答案

你读过这个 jQuery 文档了吗 Triggering Event Handlers

摘录:

How can I mimic a native browser event, if not .trigger()?

In order to trigger a native browser event, you have to use document.createEventObject for < IE9 and document.createEvent for all other browsers. Using these two APIs, you can programmatically create an event that behaves exactly as if someone has actually clicked on a file input box. The default action will happen, and the browse file dialog will display.

The jQuery UI Team created jquery.simulate.js in order to simplify triggering a native browser event for use in their automated testing. Its usage is modeled after jQuery's trigger.

基本上,整个内容可以总结如下:

function Settings() {
this.bubbles = true;
this.cancelable = true;
this.view = window;
this.screenX = 0;
this.screenY = 0;
this.clientX = 1;
this.clientY = 1;
this.ctrlKey = false;
this.altKey = false;
this.shiftKey = false;
this.metaKey = false;
this.button = 0; /* Which mouse button was pressed */
this.relatedTarget = null;
return this;
}

function simulateMouseEvent(type, target, s) {
var e = document.createEvent("MouseEvents");
e.initMouseEvent(type, s.bubbles, s.cancelable, s.view, 0, s.screenX, s.screenY, s.clientX, s.clientY, s.ctrlKey, s.altKey, s.shiftKey, s.metaKey, s.button, s.relatedTarget);
target.dispatchEvent(e);
}

var settings = new Settings, target = document.getElementById('myButton');

/* Try with something like this: */
simulateMouseEvent('mousedown', target, settings);
simulateMouseEvent('mouseup', target, settings);
simulateMouseEvent('click', target, settings);

来源:https://github.com/jquery/jquery-simulate/blob/master/jquery.simulate.js

完整参数列表如下所述:MouseEvent.initMouseEvent()

关于javascript - 如何创建一个完美的假 jQuery 事件对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60409723/

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