Method 1: setAttribute
Var obj = document. getElementById ("obj ");
Obj. setAttribute ("onclick", "javascript: alert ('test ');");
Here, setAttribute is used to specify the onclick attribute, which is simple and easy to understand,
However, IE does not support the setAttribute function, but does not support setting certain attributes with setAttribute, including object attributes, set attributes, and event attributes, that is to say, setting style, onclick, and onmouseover attributes with setAttribute does not work in IE.
Method 2: Use attachEvent and addEventListener
IE supports attachEvent
Obj. attachEvent ("onclick", Foo );
Function Foo ()
{
Alert ("test ");
}
Can also be written together
Obj. attachEvent ("onclick", function () {alert ("test ");});
Other browsers support addEventListener
Obj. addEventListener ("click", Foo, false );
Function Foo ()
{
Alert ("test ");
}
Can also be written together
Obj. addEventListener ("click", function () {alert ("test") ;}, false );
Note that attachEvent events include on, such as onclick, while addEventListener does not include on, such as click.
By the way, the third parameter of addEventListener (although rarely used) useCapture-if it is true, useCapture indicates that you want to start the capture. After capturing is started, all events of the specified type are assigned to the registered EventListener before they are assigned to any EventTargets under the tree. The events that are going to bubbling through the tree will not trigger the specified EventListener captured.
Comprehensive Application
If (window. attachEvent)
{
// IE Event code
}
Else
{
// Event code of other browsers
}
Method 3: event = Function
Example: obj. onclick = Foo;
This is supported in multiple browsers. This is an old specification (method 2 belongs to the DOM2 Specification). However, due to its ease of use, there are many applications.
The following is my solution:
Function show (){
Alert ("Hello, world !!! ");
}
Obj. setAttribute ('onclick', document. all? Eval (function () {show ()}): 'javascript: show ()');
It looks very simple. It is also compatible with browsers, that is, it does not know whether there is any other impact, or is there a better way to replace it?