简体   繁体   中英

jQuery: Prevent click on sub-element's class: redirect page on tr click EXCEPT certain td

I've been searching for like 30 minutes already, so I apologize if I missed this answer already. I've seen a lot of CLOSE ones, but none quite like this.

I have an imported JavaScript function which is used in several files. It makes it so any table whose row has a clickable-row class will redirect to the href attribute, thereby making the whole row act like an anchor tag.

However, on some pages I'll have on td be populated with a checkbox, which I want to be able to click WITHOUT the page redirecting (so I can select multiple rows in the table).

Here is my current function:

jQuery(document).ready(function() {
    jQuery('.clickable-row').click(function() {
        window.document.location = jQuery(this).attr('href');
    });
});

I want it to do something like the following, but this doesn't work:

jQuery(document).ready(function() {
    jQuery('.clickable-row').click(function() {
        if(!jQuery(this).closest('td').hasClass('skip-click')) {
            window.document.location = jQuery(this).attr('href');
        }
    });
});

Any ideas on how to handle this?

You need to use e.target .

this inside the handler will refer to the .clickable-row element, not the element which actually triggered the click. The target property of the event object will return the element that triggered the event.

jQuery(document).ready(function ($) {
    $('.clickable-row').click(function (e) {
        if (!$(e.target).closest('td').hasClass('skip-click')) {
            window.document.location = jQuery(this).attr('href');
        }
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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