Reliably adding to a JavaScript event
I have a radio button, containing an inline onclick
event:
<input type="radio" class="quantitycheckbox" onclick="alterQuantity(this.form)">
I'm trying to unobtrusively add some more functionality on click, and have this code:
function updateCustomFields( box ) {
// save current onclick event before assigning new one
var currEvent = box.onclick;
box.onc开发者_开发问答lick = function() {
currEvent();
// do additional stuff here
}
}
var boxes = $class('quantitycheckbox');
for( var i = 0; i < boxes.length; i++ ) {
updateCustomFields( boxes[i] );
}
However, the value of this.form
that's passed into the alterQuantity
function is undefined, and I get an error. How would I preserve the onclick
event as it is and add my functionality?
You don't need to do anything with the inline onclick event. Simply by attaching another event using attachEvent
or addEventListener
will solve your problem since the inline onclick
event will always fire first:
function updateCustomFields( box ) {
var myCallback = function(){
// Do stuff here
}
if(window.addEventListener){
box.addEventListener('click', myCallback, false);
} else if (window.attachEvent){
box.attachEvent('onclick', myCallback);
}
}
The execution order will be:
- Inline event
- Your new event
Try:
currentEvent.call(box);
to pass box
as the value of this
into currentEvent()
;
edit: Doug's solution is actually better. Anyway, the call
and apply
methods available to all function objects is how you alter the value of this in function calls.
精彩评论