how to make a whole row in a table clickable as a link?

前端 未结 26 1929
粉色の甜心
粉色の甜心 2020-11-22 14:05

I\'m using Bootstrap and the following doesn\'t work:


    
        
            Blah Blah
           


        
26条回答
  •  自闭症患者
    2020-11-22 14:15

    Author's note I:

    Please look at other answers below, especially ones that do not use jquery.

    Author's note II:

    Preserved for posterity but surely the wrong approach in 2020. (Was non idiomatic even back in 2017)

    Original Answer

    You are using Bootstrap which means you are using jQuery :^), so one way to do it is:

    
        
            Blah Blah 1234567 £158,000
        
    
    
    
    jQuery(document).ready(function($) {
        $(".clickable-row").click(function() {
            window.location = $(this).data("href");
        });
    });
    

    Of course you don't have to use href or switch locations, you can do whatever you like in the click handler function. Read up on jQuery and how to write handlers;

    Advantage of using a class over id is that you can apply the solution to multiple rows:

    
        
            Blah Blah 1234567 £158,000
        
        
            More money 1234567 £800,000
        
    
    

    and your code base doesn't change. The same handler would take care of all the rows.

    Another option

    You can use Bootstrap jQuery callbacks like this (in a document.ready callback):

    $("#container").on('click-row.bs.table', function (e, row, $element) {
        window.location = $element.data('href');
    });
    

    This has the advantage of not being reset upon table sorting (which happens with the other option).


    Note

    Since this was posted window.document.location is obsolete (or deprecated at the very least) use window.location instead.

提交回复
热议问题