This article mainly analyzes the differences between JS events in IE and FF in detail. If you need a friend, please refer to it, the search category in the Easy Search Project, which is helpful to everyone, is dynamically generated through JS, and each generated element must dynamically add attributes and events. You can assign values to attributes, which is applicable to IE and FF. For example:
Var element = document. createElement ('select ');
Element. id = "myselect ";
The preceding statement has the same effect in IE and FF and runs normally. However, most of the elements we create need to dynamically add events to them. Obviously, we cannot just add a dot next to the same attribute, and then write an event name, then followed by a string of code, an error will be reported. Therefore, we can use the following method to add events:
First, we need to determine which browser is the current browser, and we will continue to use the previous definition,
If (element. attachEvent ){
// For IE and IE kernels (1)
} Else if (element. addEventListener ){
// Browsers with FF and NS kernels (2)
}
The above if statement block helps us determine whether the browser is IE or FF.
The browser determines, and what we need to do is to register the function into the element. The following is a defined function:
Function showElementId (elmt ){
Alert (elmt. id );
}
The function is very simple, that is, the ID of the element in the parameter is prompted.
For IE browser, insert the following code to the comment (1) above:
Element. attachEvent ("onclick", function () {showElementId (elmt )});
For the FF browser, insert the following code to the comment (2) above:
Var eventName = "onclick". replace (/on (. *)/I, '$1 ');
Element. addEventListener (eventName, function () {showElementId (elmt)}, false );
When registering an event for an element in FF, you do not need to replace on with the event name.
Well, if you want to use JS to dynamically add events to elements in your development projects in the future, you can use the above method. In this way, you can avoid using the features you developed when using the FF browser.