Home  >  Article  >  Web Front-end  >  javascript dynamically add event code_javascript skills

javascript dynamically add event code_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:58:08922browse
Method 1, setAttribute
var obj = document.getElementById("obj");
obj.setAttribute("onclick", "javascript:alert('test');");
Here we use setAttribute to specify the onclick attribute, which is simple and easy to understand.
However: IE does not support it. It is not that IE does not support the setAttribute function, but it does not support using setAttribute to set certain attributes, including object attributes and collection attributes. , event attributes, that is to say, using setAttribute to set style, onclick, onmouseover attributes will 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 the attachEvent event has on, such as onclick, while addEventListener does not have on, such as click .
By the way the third argument to addEventListener (although rarely used) useCapture - if true, useCapture indicates that the user wishes to initiate capture. When capturing is initiated, all events of the specified type will be dispatched to the registered EventListener before being dispatched to any EventTargets below it in the tree. Events that are bubbling up the tree will not fire the EventListener specified using capture.
Comprehensive application
if (window.attachEvent)
{
//Event code of IE
}
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), but because it is easy to use, it is used in many situations.

Here is my solution:
function show(){
alert("Hello, world!!!");
}
obj.setAttribute('onclick' ,document.all ? eval(function(){show()}) : 'javascript:show()');
It seems very simple and compatible with browsers, but I don’t know if there are any other effects. Or is there a better way to replace it?
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