怎样合成一个DIV元素上的浏览器点击事件? [英] How do I synthesize a browser click event on a DIV element?

查看:154
本文介绍了怎样合成一个DIV元素上的浏览器点击事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过按钮,我可以调用点击()他们的方法已经产生点击。然而,资料核实不具备在所有浏览器此方法。然而,我可以将点击事件侦听器给他们(通过设置 .onclick =...或添加事件侦听器)。

With buttons, I can call the click() method on them to have a click generated. DIVs however don't have this method on all browsers. Yet I can attach click event listeners to them (by either setting .onclick="..." or adding an event listener).

有没有办法对我来说,合成这样的元素上点击编程,但不使用jQuery ?理想情况下,这将不依赖于听众的一种特定的方式被注册(因此简单地调用的eval(div.onclick)不会为我工作),以及工作在所有的现代浏览器。

Is there any way for me to "synthesize" a click on such an element programmatically, but without using jQuery? Ideally this will not be dependent on a specific way of the listeners being registered (so simply calling eval(div.onclick) will not work for me), and work in all modern browsers.

(对于好奇,我需要这个自动测试,不欺骗用户。)

(For the curious, I need this for automated testing, not tricking users.)

推荐答案

我最近写了一个函数,只是这做了我的图书馆,它可以在GitHub的库中的here

I recently wrote a function to do just this into my library, it can be found in the GitHub repository here.

这是完全跨浏览器和触发由选择引擎返回的元素指定的事件。我相信,你将能够c您从它需要提取$ C $。

It is completely cross browser and triggers the specified event on the elements returned by the selector engine. I am sure you will be able to extract the code you need from it.

如果不是,这里是你所需要的。更换,那么,该元素的元素。而随着事件的类型类型,在此情况下,点击

If not, here is what you need. Replace element with, well, the element. And type with the type of event, in this case, click.

// Check for createEventObject
if(document.createEventObject){
    // Trigger for Internet Explorer
    trigger = document.createEventObject();
    element.fireEvent('on' + type, trigger);
}
else {
    // Trigger for the good browsers
    trigger = document.createEvent('HTMLEvents');
    trigger.initEvent(type, true, true);
    element.dispatchEvent(trigger);
}

下面是一个例子的实现。

Here is an example implementation.

function simulateEvent(element, type) {
    // Check for createEventObject
    if(document.createEventObject){
        // Trigger for Internet Explorer
        trigger = document.createEventObject();
        element.fireEvent('on' + type, trigger);
    }
    else {
        // Trigger for the good browsers
        trigger = document.createEvent('HTMLEvents');
        trigger.initEvent(type, true, true);
        element.dispatchEvent(trigger);
    }
}

这篇关于怎样合成一个DIV元素上的浏览器点击事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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