jQuery.click(): Can I get a reference to the synthetic event object passed to event handlers?
I have an <a>
inside a <TD>
, and I'm trying to have clicks on the <TD>
, but outside the <A>
, act like they were clicks on the <a>
. I'm almost there:
HTML:
<TD class="somethingPretty">
<a href="someURL" class="anchor">Text</a>
</td>
JS:
$('.anchor').click(function(ev){return confirm("go ahead?");});
$('somethingPretty').click(function(ev){
if($('.anchor').click()){
document.location = $('.anchor').attr('href');
}
}
The problem with this is that jQuery.click
returns undefined
, and I can't see how to ge开发者_运维技巧t at the event object that's passed to the click handlers so I can interrogate it with isPropagationStopped
and isDefaultPrevented
. What's the right way to solve this problem?
Sometimes asking the question clearly is the best way to find an answer. Some strategic poking around the jQuery source led me to the following solution(using the markup above):
$('.somethingPretty').click(function(ev){
var syntheticClick = new $.Event("click");
syntheticClick.stopPropagation();
$('.anchor').trigger(syntheticClick);
if(syntheticClick.isDefaultPrevented()) return;
document.location = $('.anchor').attr('href');
}
This works for all event handlers except live-bound ones (those don't execute; my users will have to learn to click the anchor itself for them!). The tricky part here is that trigger
takes a jQuery.Event
in addition to the documented string.
How about this?
var a = $('.somethingPretty .anchor');
var td = $('.somethingPretty');
a.click( function(ev) { return confirm("go ahead?"); } );
td.click( function() { a.click(); } );
Did you try something like:
$("td.outer").add("td.outer a").click(function() {
// do stuff
});
You're going to want to find some way to ensure that whatever is in the function runs only once, since a click on the <a>
will count both as a click on the <td>
and the <a>
.
精彩评论