我想将事件绑定到弹出窗口的(动态创建的)内容。我发现“elementParse”回调返回一个inlineElement键,但它只在超时后才可用..
我怎样才能做到最好?
我的代码的简化版本:
HTML:
<div id="dynamic-content-container">
<!-- content in here is dynamically loaded, so can't do $('button').magnificPopup(); -->
<button>open lightbox</button>
</div>
<script type="text/template" id="template">
<p>some content</p>
<button class="confirm">bind event on me!</button>
</script>
JS:
// using event delegation to open lightbox
$('#dynamic-content-container').on('click', 'button', openLightbox);
function openLightbox() {
var dialogHtml = $('#template').text();
// some template parsing stuff happens here...
dialogHtml = '<div>'+ dialogHtml +'</div>';
$.magnificPopup.open({
items: {
src: dialogHtml,
type: 'inline'
},
callbacks: {
elementParse: function(item){
// I want to do something like:
// item.inlineElement.on('click', '.confirm', doConfirm);
console.log(item);
console.log(item.inlineElement); // doesn't exist yet
setTimeout(function(){
console.log(item.inlineElement); // this works, but ain't pretty
}, 1000);
}
}
});
}
答案 0 :(得分:3)
使用change
或afterChange
回调。在解析元素之前会触发elementParse
。