In order to add events we could use this simple 1st solution:
function AddEvent(html_element, event_name, event_function)
{
if(html_element.attachEvent) //Internet Explorer
html_element.attachEvent("on" + event_name, function() {event_function.call(html_element);});
else if(html_element.addEventListener) //Firefox & company
html_element.addEventListener(event_name, event_function, false); //don't need the 'call' trick because in FF everything already works in the right way
}
or this 2nd solution (that adds inline events):
function AddEvent(html_element, event_name, event_function)
{
var old_event = html_element['on' + event_name];
if(typeof old_event !== 'function')
html_element['on' + event_name] = function() { event_function.call(html_element); };
else
html_element['on' + event_name] = function() { old_event(); event_function.call(html_element); };
}
These are both cross-browsers and can be used in this way:
AddEvent(document.getElementById('some_div_id'), 'click', function()
{
alert(this.tagName); //shows 'DIV'
});
Since I have the feeling attachEvent/addEventListener
are used more around in events handling implementations, I'm wondering:
Are there any disadvantages/drawbacks against using the 2nd solution that I might better be aware of?
I can see two, but I'm interested in more (if any):
- the 2nd solution screws up innerHTML of elements by adding events inline
- Using 2nd solution I can easily remove all functions associated with a certain event type (
html_element['on' + event_name] = null
), but I can not use detachEvent/removeEventListener
to remove exactly a specific function.
Any answers like: "use jQuery" or any other FW are pointless!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…