【发布时间】:2017-09-26 12:37:47
【问题描述】:
目标是报告用户在该表中单击的 html 表的行号 - 问题是用户单击了哪个 tr 元素?
当信息通过 html 硬编码在表格中时,我能够做到这一点,使用以前的帖子 How to tell which row number is clicked in a table?
我的挑战是因为表格是通过 javascript 动态加载的,所以我无法在 html、javascript 和 jQuery 之间正确链接。当我点击动态生成的表格中的一行时,我无法传达我正在这样做。
我正在研究一个 jQuery 类,并期待更好地理解如何思考这样的问题。但是在一些事情上获得帮助确实很好,这样我在学习过程中就有了一些很好的例子。
下面是代码,现在可以使用,使用的是 Ozan 建议的代码。
<!DOCTYPE HTML>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Make Table</button>
<div id="container"></div>
<title>Board A</title>
<script type="text/javascript" charset="utf-8"></script>
<script src="mainTest.js"></script>
</head>
<center>
<img src="MarmotNapping.jpg" alt="Marmot"
height="150" width="400"
>
</center>
<body>
<p> Click in this line </p>
<script>
/*
// First Stackoverflow question I used
How to tell which row number is clicked in a table?
https://stackoverflow.com/questions/4524661/how-to-tell-which-row-number-is-clicked-in-a-table
You can achieve this with delegated event handling.
Use jQuery's .on(eventName, selector, handler) method to attach the handler to an element you know will always be present, e.g. document.
*/
//https://stackoverflow.com/questions/38820078/using-jquery-to-determine-table-row-user-clicking-on-when-table-loaded-dynamic
// begin new
$(document).on("click", "tr", function(e) {
var index = $(this).index(); //this is event.target, which is the clicked tr element in this case
console.log(index);
alert('0.You clicked row '+ ($(this).index()+1) );
});
$("button").on("click", function() {
$("table").remove();
var table = $("<table>").appendTo("#container");
for (i = 0; i < 10; i++) {
$("<tr>").append($("<td>").text("This is " + i + ". row.")).appendTo(table);
}
});
// end new
$(document).ready(function(){
$("p").click(function(){
alert("The paragraph was clicked.");
});
});
$('#QuestionsAnswersTable').find('tr').click( function(){
alert('1.You clicked row '+ ($(this).index()+1) );
});
$('#QuestionsAnswersTable').find('tr').click( function(){
var row = $(this).find('td:first').text();
alert('2.You clicked ' + row);
});
</script>
</body>
</html>
【问题讨论】:
标签: javascript jquery html