javascript - Ajax 重新加载后,onclick 功能不起作用
问题描述
我的 onclick 功能只在第一次工作。在 onclick 函数触发 ajax 请求后,在成功函数内部,我重新加载了一个包装从 SQL 检索值的代码并使用 for 循环构建 html 表的代码。
尽管它正确刷新了表格(它正确地从 db 添加了新值),但当我单击表格元素时,onclick 函数会停止反应。但是当我刷新表格时,它又开始工作了,但仍然只有 1 次
我究竟做错了什么?
这是我与 Ajax 一起使用的 onclick 函数:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#main tbody').on('click', 'td', function () {
$irow = $(this).parent().index();
$icol = $(this).index();
console.log(" row and column: ");//to debug
console.log($irow);//to debug
console.log($icol);//to debug
$.ajax({
type: "POST",
url: "check_db.php",
data: { 'srow' : $irow,
'scol' : $icol
},
success: function(data) {
alert(data);
console.log(data);
$("#view").load(" #view > *")
}
});
});
});
</script>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
这是我在 div 中的代码
<body>
<h1>Welcome <?php echo $_SESSION["username"] ?> </h1>
<div id="view">
<?php
$sql = "SELECT username, row, col FROM seats";
$result = $link->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$outer_array[]=$row;//FILLING OUTER_ARRAY EACH ROW AS SEPERATE ARRAY.
// echo "<br>"."username: " . $row["username"]. " - row: " . $row["row"]. " col: " . $row["col"]. "<br>";
}
}else{
echo "0 results";
}
//======================Loop to create table starts from here!!!=================================
$nrows= 9; // Number of rows in table
$counter_row=0;//counter to use inside loop to match desired row value
$ncols=6;// Number of columns in table
$counter_col=0;//counter to use inside loop to match desired column value
echo '<table id = "main" style="width:100%"><tbody>';
for ($row = 0;$row<$nrows;$row++) {
echo "<tr>";
for ($col = 0;$col<$ncols;$col++) {
for ($i = 0;$i<count($outer_array);$i++) {
if (($outer_array[$i]['row']==$counter_row)&&($outer_array[$i]['col']==$counter_col)){
$uname = $outer_array[$i]['username'];
break;
} else {$uname = "free";}
}
if ($uname=="free"){
echo "<td style = background-color:green;color:black> </td>";
}elseif($uname!= $_SESSION["username"])
{ echo "<td style = background-color:yellow;color:black>$uname</td>";
} else echo "<td style = background-color:orange;color:black>$uname</td>";
$counter_col++;
if($counter_col==$ncols){$counter_col=0;}//to reset counter column at the end of each row
}
echo "</tr>";
$counter_row++;
}
echo '</tbody>';
echo '</table>';
?>
</div>
解决方案
使用第一个静态元素(#view
在您的情况下)作为您的事件委托者:
$('#view').on('click', 'td', function () {
为了进一步解释,由于 AJAX 成功后您重建了 static 的全部内容#view
,因此 TBODY in$('#main tbody')
是一个全新的元素,它不再委托初始点击事件。
推荐阅读
- c# - ASP.NET 的所有危险字符组合列表?
- c++ - 将函数简单生成为 std::thread
- python - Pandas 过滤多列和多行
- syslog - ubuntu 20.04 和海量日志
- css - 缩小图像以适应 div 而不是扩展 div 以适应
- python - 有没有办法在没有第三方的情况下创建电子邮件服务器?
- javascript - “端口”包到一个新名称 npm
- java - 从用 Android Studio 编写的 Login 类创建 Java 单元测试
- python - 如何在不添加括号和双空格的情况下从数组列表中创建数据框?
- javascript -
我无法将事务和事件处理结合起来工作