在准备好文档时,我有一个页面调用ajax并显示结果表。
可以通过单击按钮来更新行,然后按钮会调用将更新发布到服务器的功能。
我没有在文档就绪功能中包含click功能,但是一旦我将它们组合起来它就不起作用。
HTML
<div id="newreqs"></div>
的Javascript
$(document).ready(function(){
$('.approveCredit').on('click', function(e) {
e.preventDefault();
var creditid = $(this).attr('creditid');
var allocatedcreds = $(this).attr('allocatedcreds');
$.ajax({
url: "assets/ajax/addcustomer.php",
type: "POST",
data: {creditid: creditid,allocatedcreds: allocatedcreds},
success: function(result){
alert('Credit Applied!');
},
error: function(exception){
alert('Exception:' +exception);
}
});
});
$.post('assets/ajax/calldata/newreqs.php', function(data) {
$('#newreqs').html(data)
});
});
所谓的数据
<table class="table table-hover">
<thead>
<tr>
<th class="text-center" style="width: 50px;">#</th>
<th class="hidden-xs" style="width: 15%;">Name</th>
<th class="hidden-xs" style="width: 15%;">Requested Credits</th>
<th class="hidden-xs" style="width: 15%;">Notes from User</th>
<th class="hidden-xs" style="width: 15%;">PO</th>
<th class="hidden-xs" style="width: 15%;">Date Requested</th>
<th class="hidden-xs" style="width: 15%;">Status</th>
<th class="text-center" style="width: 15px;">Actions</th>
</tr>
</thead>
<tbody>
<?php
$count = 1;
while ($row = mysql_fetch_array($test))
{?>
<tr>
<td class="text-center"><?php echo $count++;?></td>
<td><?php echo $row['user_id'];?></td>
<td><?php echo $row['credits'];?></td>
<td><?php echo $row['notes'];?></td>
<td><?php echo $row['po'];?></td>
<td><?php echo $row['date_received'];?></td>
<td><?php echo $status;?></td>
<td class="text-center">
<div class="btn-group">
<a class="btn btn-xs btn-default approveCredit" type="button" allocatedcreds="<?php echo $row['credits'];?>" creditid="<?php echo $row['id'];?>" data-toggle="tooltip" data-original-title="Approve Credit Request"><i class="fa fa-check"></i></a>
</div>
</td>
</tr>
<?php } ?>
</tbody>
</table>
如上所述,当我不在文档就绪函数中包含click函数时,这会起作用,但是,当包含任何内容都无效时。
我加入click功能的原因是因为我想在服务器上更新数据后创建一个页面刷新。
答案 0 :(得分:4)
这是事件委托的用例,更改为:
$(document).on('click', '.approveCredit', function(e) {
$(document)
可以替换为静态父级:
$('#newreqs').on('click', '.approveCredit', function(e) {
当页面加载时,按钮不存在,并且该元素的事件无法注册。所以可以做的是将事件委托给静态父或document
本身。