簡體   English   中英

通過使用jquery單擊表的行,將行的信息顯示到右側div中

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

對於我最近的項目,我需要在表中顯示數據。 當我單擊表的任何行時,該行的所有內容將顯示在另一個div中。 請參見下面的代碼:

<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>

請提出有關如何使用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> 

將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>

提示:如果您了解jQuery,則比普通的JavaScript更喜歡jQuery。 這將導致更簡潔的代碼。

只需在您的示例中添加點擊功能:

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

添加此代碼:

<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