jQuery: Get return of an onclick-function from an anchor
Is there a way to get the return-value of an onclick-function like confirm
into a jQuery-function?
I have links which have an onclick-event for confirmation which returns true or false:
<a onclick="return confirm('Sure?');" class="delete" href="delete.php">Delete</a>
This is a given structure and I have no possibility in changing it. But I would like to do so开发者_如何学Cmething like this:
$('a.delete').click(function() {
if (confirm_from_onclick == true) {
//do some more before really returning true and following the link
}
});
If there is no way for you to change the HTML markup, you need to remove the complete onclick
inline-handler from that node and to it in your unobtrusive event handler.
This could look like:
$(function() {
$('a').each(function(_, anchor) {
var onclk = anchor.onclick; // store the original function
anchor.onclick = null; // delete/overwrite the handler
$(anchor).bind('click', function() {
if( onclk() ) {
// do something
}
return false; // call stopPropagation() + preventDefault()
});
});
});
Since you're dealing with an onclick
inline-event handler, you cannot stop or prevent that from firing with an unobtrusively bound event handler. It'll always fire first, so you need to completely remove the original event.
You don't really need to store the function, you also could just set the onclick
to null
and rewrite the logic in your own event handler. I did it for convenience only.
Demo: http://jsfiddle.net/em9KP/
Really simple answer and might not be exactly what you're looking for, but why not remove the "onclick" event from the anchor, then handle everything inside the click function?
As in, create the confirm dialog inside the function.
<a class="delete" href="delete.php">Delete</a>
$('a.delete').click(function(e) {
e.preventDefault();
if (confirm('Sure?')) {
//do some more before really returning true and following the link
}
});
EDIT: Sorry! Missed the part where you mentioned that it's a set structure and you have no way of changing it. Working on an alternative.
精彩评论