Javascript 使用jquery捕获引导模式中动态按钮的单击事件
我有一个引导模型如下Javascript 使用jquery捕获引导模式中动态按钮的单击事件,javascript,jquery,html,bootstrap-modal,Javascript,Jquery,Html,Bootstrap Modal,我有一个引导模型如下 <div class="modal fade" id="PQModel" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-cont
<div class="modal fade" id="PQModel" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title " id="exampleModalLongTitle"><strong>Priority Queue Selection</strong></h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body justify-content-center">
<div id="modal-text"></div>
</div>
<div class="modal-footer justify-content-center">
<button type="button" class="btn btn-danger cancel">Cancel</button>
</div>
</div>
</div>
</div>
模态按预期进行,按钮按预期进行。但是点击我无法捕获按钮点击事件。我不确定我哪里出错了。请帮我解决这个问题。我怀疑在您完成对象的生成和显示之前,正在为单击功能绑定对象。为了确保这一点,请使用以下简单的代码块替换第三个代码块
console.log($(“#PQModel#modal text div.btn”))
并验证在调用此函数时,是否确实正在选择对象在DOM元素存在之前,您正在附加一个
单击事件。这意味着事件侦听器未附加任何内容
您需要使用事件委派来正确处理这种情况。这会将一个事件侦听器附加到父容器上,每当在容器内单击时,它就会确定元素是否与提供的辅助选择器(div.btn)匹配
非常感谢。您为我节省了很多时间…我应该在结束之前询问,您是在循环之前还是之后执行事件绑定?
var scrn = '';
$.each(pqueueList, function(index, val)
{
scrn += ' <div class="row justify-content-center top-buffer">';
scrn += ' <div class="col-6">';
scrn += ' <div class="btn btn-block';
if (val["fieldType"] == "EVEN"){
scrn += ' btn-primary ';
}
else{
scrn += ' btn-success ';
}
scrn += '" value="'+val["pqId"]+'"><h2>'+val["pqName"]+'</h2></div>'
scrn += ' </div>';
scrn += '</div>';
});
$('#modal-text').html(scrn);
$("#PQModel").modal('show');
}
$("#PQModel #modal-text div.btn").on('click',function(){
var value = $(this).attr('value');
alert("value "+ value);
});
$("#PQModel #modal-text").on('click','div.btn', function(){
var value = $(this).attr('value');
alert("value "+ value);
});