Home >Web Front-end >JS Tutorial >Javascript simulates click events (click links and html clicks) compatible with IE/Firefox_javascript skills

Javascript simulates click events (click links and html clicks) compatible with IE/Firefox_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:37:252010browse

There are generally two aspects of simulating clicks in one situation, simulating clicks on hyperlink events
The compatible functions of firefox are
Add onclick event to HTMLAnchorElement

Copy code The code is as follows:

try {
// create a element so that HTMLAnchorElement is accessible
document. createElement('a');
HTMLElement.prototype.click = function () {
if (typeof this.onclick == 'function') {
if (this.onclick({type: 'click '}) && this.href)
window.open(this.href, this.target? this.target : '_self');
}
else if (this.href)
window .open(this.href, this.target? this.target : '_self');
};
}
catch (e) {
// alert('click method for HTMLAnchorElement couldn't 't be added');
}

The following is the specific application

[Ctrl A Select all Note: If you need to introduce external Js, you need to refresh to execute
]

If it is an ordinary html addition Click
to make FireFox's HTMLElement have a click method (add click method to HTMLElement in Mozilla) The code is as follows :


try {
// create span element so that HTMLElement is accessible
document.createElement('span');
HTMLElement.prototype.click = function () {
if (typeof this.onclick == 'function')
this.onclick({type: 'click'});
};
}
catch (e) {
// alert('click method for HTMLElement couldn't be added');
}


The following are other related articles from netizens that you can also refer to.
When I was working on something recently, I found that the user’s behavior of pressing Enter in the input box of the web page is not fixed. . .
Especially when the web page has multiple forms
So I searched and found a js that simulates clicks. After testing, it can run on firefox and IE The code is as follows:


function doClick(linkId, e){
if(e.keyCode != 13){
return;
}
var fireOnThis = document.getElementById(linkId)
if (document.createEvent)
{
var evObj = document.createEvent('MouseEvents')
evObj. initEvent( 'click', true, false )
fireOnThis.dispatchEvent(evObj)
}
else if (document.createEventObject)
{
fireOnThis.fireEvent('onclick')
}
}


where e is event, a built-in object, and linkId is the object id that simulates being clicked
For example,
In this case, the user can press Enter to submit the form~
opera can change it again The code is as follows:


click me

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn