i have a div that contains a table
<div id="container">
<table id="data">
<tbody>
......
......
</table>
</div>
i have bindind the onclick event on table rows so that if the user clicks a row, it is highlighted
$("#data tr").mouseup(function()开发者_如何学JAVA {
$("tr.selected").removeClass("selected");// Deselect currently selected rows
$(this).addClass("selected");
});
now if the user clicks somewhere outside the table, i want to deselect the row. the problem is if i bind the click event with the div, both the table and the div gets the callback...how can i only get a callback for the div? so that i can deselect the rows!! i even tried binding the onClick with the body element but it luks like if u bind an event with an element, all the elements inside it will get the callback. if thats the case how can i deselect the rows then if user clicks outside the bounds of table.
This is caused by the bubbling of nested elements. You can stop that by using
$("div").click(function(e) {
if($(this).attr('id')=="data")
{
e.stopPropagation();
return;
}
$(".selected").removeClass("selected");
});
$("#data tr").mouseup(function() {
$("tr.selected").removeClass("selected");// Deselect currently selected rows
$(this).addClass("selected");
});
From: http://api.jquery.com/event.stopPropagation
精彩评论