How do I synthesize a browser click event on a DIV element?

╄→гoц情女王★ 提交于 2019-12-07 07:30:30

问题


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).

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.)


回答1:


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

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);
    }
}



回答2:


If your browser is DOM compatible you can use the dispatchEvent(evt) method of the DIV element.

For more see the dom w3c spec.



来源:https://stackoverflow.com/questions/5159806/how-do-i-synthesize-a-browser-click-event-on-a-div-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!