Home > Web Front-end > JS Tutorial > Detailed analysis of the difference between JS events in IE and FF_javascript skills

Detailed analysis of the difference between JS events in IE and FF_javascript skills

WBOY
Release: 2016-05-16 17:13:58
Original
924 people have browsed it

The search categories in

Zhidao's Yisou project are dynamically generated through JS, and attributes and events must be dynamically added to each generated element. Among them, adding attributes can be done by assigning values, which is applicable to both IE and FF. For example:

var element = document.createElement('select');

element.id = "myselect";

The above statement will have the same effect in IE and FF and run normally. But most of the elements we create need to dynamically add events to them. Obviously, we can't directly add a dot at the end like adding attributes, and then write an event name, and then follow it with a string of code, otherwise an error will be reported. of. So we can use the following method to add events:

First of all: we need to determine what browser the current browser is. We still use the previous definition,

if( element.attachEvent ){

//For IE and browsers with IE core (1)

}else if( element.addEventListener){

//Browsers with FF and NS cores (2)

}

The if statement block above helps us determine whether the current browser is IE or FF.

The browser determines it, and then all we have to do is register the function into the element. Below we give a functional function we defined:

function showElementId(elmt){

alert(elmt.id);

}

The function function is very simple, it is to prompt the ID of the element in the parameter.

If it is IE browser, we insert the following code into comment (1) above:

element.attachEvent( "onclick",function(){showElementId(elmt)});

If it is FF browser, we insert the following code into comment (2) above:

var eventName = "onclick".replace(/on(.*)/i,'$1');
element.addEventListener( eventName,function(){showElementId(elmt)},false);

Because when registering an event for an element in FF, there is no need for "on" in front of the event name, so on must be replaced.

Okay, if in the future, colleagues in the development project encounter the need to use JS to dynamically add events to elements, you can use the above method. That way you can prevent users from being unable to use the functions you've worked so hard to develop when using FF Browser.

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template