I have a table with some rows and I am using jQuery to apply a click e开发者_运维百科vent to the TRs
$("tr").click(function(e)
{
console.log($(this).data("rowid"));
});
That works fine. One of the TDs, I have an actual link and when I click the link, I still get the console.log to print out. Is there a way to exit that click function if I am clicking the link?
Call event.stopPropagation();
$('td a').click(function(event) {
event.stopPropagation();
});
This will prevent the parent <tr>
element's click event from firing when you click on a link that's within a <td>
.
Here's a working example: http://jsfiddle.net/ALUZy/
You should probably add a class type where your method should not be applied
Skip any anchors:
$("tr").click(function(e)
{
if (e.target.tagname.toLowerCase() == 'a')
return; // Do nothing.
console.log($(this).data("rowid"));
});
I would change your logic to detect column clicks, and after checking the column that was clicked, execute your console.log on the row.
$('td').click(function(){
if ($(this).not('a')){
console.log($(this).closest('tr').data("rowid"));
}
});
You could do something like this:
$("tr").each(function(t){
if($("a", this).length == 0){
$(this).click(function(e) {
console.log($(this).data("rowid"));
}
}
});
To only apply that click function to table rows that do not contain anchors. If you want to still apply it to that row, except for the td with the <a>
, use $("td").each(...)
instead, and $(this).parent().data("rowid"))
精彩评论