模式警报,但确认按钮未对脚本做出反应

Modal alert but confirm button not reacting to script

本文关键字:脚本 按钮 确认 模式      更新时间:2023-09-26

当用户想要从那里的作品集中删除项目时,我正在尝试发出动态模式弹出警报。

我对弹出窗口本身没有任何问题,并且从项目中获取 ID 与模态视图一起解析,但是......

模态

视图中的按钮是从脚本生成的,如小提琴所示,当我单击模态中的"删除"按钮并希望它激活.js功能时,没有任何反应???

我错过了什么,还是有其他方法可以做到这一点?

.js:

$('.delete').click(function(){
    var pid = $(this).attr("data-id");
    var pname = $(this).attr("data-name");
    $(".delete-footer").html('<button type="button" class="btn btn-warning" data-dismiss="modal">Regret</button><a href="#" data-id="'+pid+'" class="btn btn-info do_delete">Delete</a>');
    $('#confirm-delete').modal('show');
});
$('.do_delete').click(function(){
    alert("I am here!");
    var pid = $(this).attr("data-id");
    $('#confirm-delete').modal('hide');
});

.html:

<a href="#" class="delete" data-id="23">Delete the project</a>
<div class="modal fade" id="confirm-delete" data-backdrop="static">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Delete project?</h4>
            </div>
            <div class="modal-body delete-body">
                Are you sure you want to delete project?                
            </div>
            <div class="modal-footer delete-footer">
            </div>
        </div>
    </div>
</div>

链接到小提琴

任何帮助都值得赞赏,提前感谢:-)

你需要以这种方式绑定事件

$(document).on('click', '.do_delete', function(){
    alert("I am here!");
    var pid = $(this).attr("data-id");
    $('#confirm-delete').modal('hide');
});

原因

因为您正在将元素动态添加到文档中。您用于绑定单击事件的方式可确保仅绑定到文档首次准备就绪时存在的那些元素。

动态添加的元素不会获取绑定。我们需要使用 JQuery 的 .on() 来做这些。

$('.delete').click(function(){

var pid = $(this).attr("data-id");
var pname = $(this).attr("data-name");
$(".delete-footer").html('<button type="button" class="btn btn-warning" data-dismiss="modal">Regret</button><a href="#" data-id="'+pid+'" class="btn btn-info do_delete">Delete</a>');
$('#confirm-delete').modal('show');

$('.do_delete').click(function(){
alert("I am here!");
var pid = $(this).attr("data-id");
$('#confirm-delete').modal('hide');

});});