简体   繁体   中英

can you bind .click() so that it fires prior to onclick?

I'm writing jQuery for an app that's being build in JSF. The JSF components are using a lot of their own JS for doing whatever JSF does and they use a lot of onclick attributes to handle it all.

Is there valid/proper way to bind your own click event to an element and ensure that your event fires prior to the default onclick event? It appears that by default a jQuery click function is fired after any inline onclick function calls.

In jQuery events are triggered strictly in the order in which they were registered.

You can circumvent any inline DOM0 onclick style handlers by iterating over the whole DOM, removing those onclick properties, and then registering your own handler which then invokes the originally defined function.

Something like:

$('[onclick]').each(function() {
    var handler = $(this).prop('onclick');
    $(this).removeProp('onclick');
    $(this).click(handler);
});

See http://jsfiddle.net/alnitak/2SCTK/

So, register your own handlers first with jQuery, then invoke the code above to remove the original inline onclick handlers and re-register them as if jQuery had added them.

EDIT code simplified to just use the original function - jQuery will ensure that the function is invoked with the right context. Previous code which explicitly set the context to window was incorrect.

You can remove the onClick event from the DOM element, and then rebind it using jQuery.

<div id="click" onclick="alert('DOM')">CLICK ME</div>

$('#click').click(function(){
    alert('jQuery');
});

var clickFunc = $('#click').prop('onclick');
$('#click').removeProp('onclick');
$('#click').click(clickFunc);

Events are called in the order they are bound, so the only way to call your function first, is to unbind, and then rebind the original function.

Demo: http://jsfiddle.net/wYd5t/2/

There is no way to mandate event firing order for the same listener on the same element. Every browser is free to fire the events in any order it chooses.

你可以在元素上使用onmousedown

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM