简体   繁体   English

jQuery:整个表格行突出显示,但单击某些子元素时除外

[英]jQuery: Whole table row highlight except when certain child elements are clicked

My question is how do I make a parent clickable using jQuery, but exclude certain child elements (eg: checkbox or a hyperlink) from being clicked? 我的问题是如何使用jQuery使父级可单击,但不单击某些子元素(例如复选框或超链接)? And at the same time, I want to allow the child elements to be clicked themselves (eg: the hyperlink needs to work? 同时,我希望允许自己点击子元素(例如:超链接是否需要工作?

To elaborate, when a row inside a table is clicked, I want it to add a checked class to the row to highlight it. 详细地说,当单击表中的一行时,我希望它向该行添加一个选中的类以突出显示它。

I have a checkbox within each row that toggles the checked class already. 我在每行中都有一个复选框,可以切换已选中的类。 So I plan to use trigger() to click this checkbox when the row is clicked. 因此,我计划在单击行时使用trigger()单击此复选框。 You'll see in my JSFiddle example . 您将在我的JSFiddle示例中看到。

The problem I am having is if they click the checkbox itself or a hyperlink within the row, I don't want it to trigger the click. 我遇到的问题是,如果他们单击复选框本身或行中的超链接,我不希望它触发单击。

I was hoping using a selector such as $('td :not(a,input)') would work but obviously I don't understand clicking child elements properly as this does not work. 我希望使用选择器,例如$('td :not(a,input)')可以工作,但显然我不正确地单击子元素,因为这不起作用。

In my same JSFiddle example you'll notice in the default example if you click the checkbox 在我的同一JSFiddle示例中,如果您单击复选框,则会在默认示例中注意到

I've been browsing the web for an answer but no one seems to be doing exactly what I'm trying to achieve. 我一直在浏览网络以寻找答案,但似乎没有人在完全按照我的目标去做。

You could probably replace this: 您可能可以替换为:

$('td :not(a,button,.custom-checkbox)').on('click', function() {
    $(this).closest('tr').find('input').trigger('click');
});

For this 为了这

$('td').on('click', function(e) {
  var $target = $(e.target); //This will get the element that is actually being clicked      
  if (!$target.is("a,button,.custom-checkbox, [type=checkbox]")) {
    //If the element being clicked doesn't belong to the group of the "unclickable" elements
    //I also added checkboxes to the "unclickable" elements
    $(this).closest('tr').find('input').trigger('click');
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM