[英]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.