我使用 PHP 和 Javascript 构建了一个像数据视图这样的项目。 在我的页面上,它有一个使用分页的用户表。每一行都有删除按钮。当我在第一页上单击该按钮时,它可以正常工作。当我单击下一页每一行的删除按钮时,看起来弹出窗口不再工作。下面是我的代码:
用于运行弹出窗口的 Javascript:
$(".mb-control").on("click",function(){
var box = $($(this).data("box"));
if(box.length > 0){
box.toggleClass("open");
var sound = box.data("sound");
if(sound === 'alert')
playAudio('alert');
if(sound === 'fail')
playAudio('fail');
}
return false;
});
$(".mb-control-close").on("click",function(){
$(this).parents(".message-box").removeClass("open");
return false;
});
PHP 脚本中用于删除按钮的 HTML(在函数中,$i对于每行的唯一 id 都是可变的)
<?php
echo "<td>
<button class='btn btn-warning mb-control btn-sm' href='./function/liststaff.remove.php?remove=".$getdata['username']."' data-box='#message-box-warning".$i."'>Remove <i class='glyphicon glyphicon-remove-circle'></i></button></a>
<div class='message-box message-box-warning animated fadeIn' id='message-box-warning".$i."'>
<div class='mb-container'>
<div class='mb-middle'>
<div class='mb-title'><span class='fa fa-warning'></span> Warning</div>
<div class='mb-content'>
<p>Are you sure want to delete user <strong>".$getdata['username']." </strong>?.</p>
</div>
<div class='mb-footer'>
<div class='pull-right'>
<a href='index.php?delete=".$getdata['id']."' class='btn btn-success btn-lg'>Yes</a>
<button class='btn btn-default btn-lg mb-control-close'>No</button>
</div>
</div>
</div>
</div>
</div>
</td>";
?>
请帮忙。
动态创建的元素上绑定单击事件,如下第二页 DOM 上不存在类名 mb 控件的按钮,因此该事件仅附加到现有元素。
希望它能帮助你。
$("body").on("click",".mb-control-close",function(){
$(this).parents(".message-box").removeClass("open");
return false;
});
$("body").on("click",".mb-control",function(){
var box = $($(this).data("box"));
if(box.length > 0){
box.toggleClass("open");
var sound = box.data("sound");
if(sound === 'alert')
playAudio('alert');
if(sound === 'fail')
playAudio('fail');
}
return false;
});
我认为包含按钮的分页行无法绑定到单击事件,因为它们是动态创建的:
试试这个:
$(document).on('click','.mb-control-close', function (event) {
$(this).parents(".message-box").removeClass("open");
return false;
});
斯菲德尔
对于动态内容上的事件绑定,不应使用直接事件,而应改用委托事件。看看这里。