jQuery trigger('click') problem
I have clickable row, that will fire link onclick
event, but trigger()
cause a new click event on tr.clickable
and go into loop. How to prevent this ?
<table>
<tr class="clickable">
<td>Test row</td>
<td><a href="#" onclick="alert('click');" class="trigger"></a></td>
</tr>
</table>
js:
$('tr.clickable').click(fu开发者_开发百科nction(){
var trigger = $(this).find('a.trigger');
trigger.trigger('click');
});
Live demo here.
This is down to event bubbling in JavaScript. It's a bit of a weird setup you've got at the moment, but one way to fix it would be to stop the click
event bubbling on the a
tag:
$('tr.clickable a').click(function (e) {
e.stopPropagation();
});
Fiddle
Alternately you could not fire the click
trigger if the target event is the same element:
$('tr.clickable').click(function(e){
var trigger = $(this).find('a.trigger').not(e.target);
trigger.trigger('click');
});
Fiddle
The best way would probably be the first solution, I guess.
remove trigger.trigger('click');
and thats it :)
Try this script
$('tr.clickable').click(function(){
alert('Click');
});
Live demo
I would suggest using the event parameter, to check what is the target of the click.
$('tr.clickable').click(function(e){
if (e.target.nodeName != 'A') {
var trigger = jQuery(this).find('a.trigger');
trigger.trigger('click');
}
});
精彩评论