简体   繁体   中英

How do click row table in modal bootstrap?

I have bound data in a table and show them in modal bootstrap. I want get data of row table using click or double click , but it's not working 在此处输入图片说明

   <div class="modal-body">
                <table id="table_search" class="table table-hover">
                    <thead>
                        <tr>
                            <td>CCA</td>
                            <td>Name</td>
                        </tr>
                    </thead>
                    <tbody>  
                    </tbody>
                </table>
            </div>

And I use jquery as follows

 $('#table_search > tbody > tr').click(function () {
            alert( $(this).val());
        });

        $('#table_search > tbody > tr').dblclick(function () {
            alert($(this).val());
        });

But it is not working.

The problem is that "click" is binding the element before it even exists. You'll have to rebind after the rows have been added to the DOM, or bind a parent structure to any child selector with "on":

 $('#table_search > tbody').on('click', '>tr', function () {
        alert( $(this));
    });

    $('#table_search > tbody').on('dblclick', '>tr', function () {
        alert($(this));
    });

I think you should be using an event delegate here or attaching the events when the modal is shown. Also tr doesn't have a value you want the text

$(document).on('click dblclick', '#table_search > tbody > tr', function (e) {
   alert($(this).text());
});

Here is a working fiddle. The others beat me to the core of the solution. I bascially have a combination of their answers in the fiddle.

https://jsfiddle.net/stephen_hartzell/seapkzvv/

The HTML

<div class="modal-body">
            <table id="table_search" class="table table-hover">
                <thead>
                    <tr>
                        <td>CCA</td>
                        <td>Name</td>
                    </tr>
                </thead>
                <tbody>  
                    <tr>
                        <td>1</td>
                        <td>2</td>
                        <td>3</td>
                    </tr>
                    <tr>
                        <td>a</td>
                        <td>b</td>
                        <td>c</td>
                    </tr>
                </tbody>
            </table>
        </div>

The Javascript

$('#table_search > tbody').on('click', '>tr', function () {
     alert( $(this).text());
});


$('#table_search > tbody > tr').dblclick(function () {
    alert($(this).text());
});

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