简体   繁体   English

通过使用jquery单击表的行,将行的信息显示到右侧div中

[英]Show a row's information into a right side div by clicking a table's row using jquery

For my recent project, I need to show data in a table. 对于我最近的项目,我需要在表中显示数据。 When I click on any row of the table, all the contents of the row will be shown in an additional div. 当我单击表的任何行时,该行的所有内容将显示在另一个div中。 See the code below: 请参见下面的代码:

<div class="left-side">
    <table id="data">
        <tr>
            <td>cell(1,1)</td>
            <td>cell(1,2)</td>
            <td>cell(1,3)</td>
        </tr>

        <tr>
            <td>cell(2,1)</td>
            <td>cell(2,2)</td>
            <td>cell(2,3)</td>
        </tr>

        <tr>
            <td>cell(3,1)</td>
            <td>cell(3,2)</td>
            <td>cell(3,3)</td>
        </tr>
    </table>
</div>

<div class="right-side">
    <!-- when a row is clicked, then the respective information is shown here-->
    <!-- for example, if i click the first row, then it shows cell(1,1) and cell(1,2) and cell(1,3) and so on-->
</div>

Please suggest any idea of how to do it using jQuery or JavaScript. 请提出有关如何使用jQuery或JavaScript的任何想法。

 var string = ''; $("#data tr").click(function() { $(this).find("td").each(function(index) { string += $(this).text(); }); document.write("<br/>" + string); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="left-side"> <table id="data"> <tr> <td>cell(1,1)</td> <td>cell(1,2)</td> <td>cell(1,3)</td> </tr> <tr> <td>cell(2,1)</td> <td>cell(2,2)</td> <td>cell(2,3)</td> </tr> <tr> <td>cell(3,1)</td> <td>cell(3,2)</td> <td>cell(3,3)</td> </tr> </table> </div> <div class="right-side"></div> 

Add a click event handler to your jQuery code: 将click事件处理程序添加到您的jQuery代码中:

<script type="text/javascript">
    $(function() {
        $("#data tr").click(function() { //Click event handler for the table column
            var columnText = $(this).text(); //text from the column clicked.
            $(".right-side").text(columnText); //Populates the .right-side div with the text.
        });
    });
</script>

Tip: If you know jQuery, then prefer jQuery over plain JavaScript. 提示:如果您了解jQuery,则比普通的JavaScript更喜欢jQuery。 It'll lead to a much cleaner and concise code. 这将导致更简洁的代码。

Just add a click function to your eg: 只需在您的示例中添加点击功能:

function showInrightDif(this) 
{
    var divtext=''
    $(this).find('td').each(function() {
       divtext = divtext + $(this).text;
    });
    $('.right-side').text(divtext);
}

add this code : 添加此代码:

<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
    $('#data tr').click(function () {
        $('.right-side').text($(this).text());
    });
</script>

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

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