The differences between the JS events in IE and FF are resolved in detail

  • 2020-03-29 23:54:18
  • OfStack

The search category in the easy search project of tao is generated dynamically by JS, and each generated element needs to dynamically add attributes and events. Among them, attributes can be added by assignment, which is applicable to both IE and FF. Such as:

        Var element = document. The createElement method (' select ');

        Element. Id = "myselect";

The above statement will have the same effect in IE and FF and will work fine. But most of the elements that we create are dynamically adding events to them, and obviously we can't just dot them, and then write the event name, and then a bunch of code, just like we did with the attributes, that's going to give us an error. So we can add events in the following way:

First of all, we need to determine what the current browser is.

    If (element. AttachEvent) {

      // browser for IE and IE kernel (1)

    {} else if (element. The addEventListener)

        // browser for FF and NS kernel (2)

    }

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

The browser recognizes that, and then all we have to do is register the function inside the element. Here is a function we defined:

    The function showElementId (elmt) {

        Alert (elmt. Id);

    }

The function simply prompts for the ID of the element in the argument.

For Internet explorer, we insert the following code into the comment (1) above:

Element. AttachEvent (" onclick ", function () {showElementId (elmt)});

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

Var eventName = "onclick". The replace (/ on/I (. *), "$1");
Element. The addEventListener (eventName, function () {showElementId (elmt)}, false);

Because you don't need the "on" before the event name to register an event for an element in FF, you replace the "on" with the "on".

Well, if your peers in future development projects want to use JS to dynamically add events to elements, you can use the above method. This will prevent users from using the FF browser without being able to use the features you've worked so hard to develop.


Related articles: