我想在一个装有ajax的popover中触发一些按钮,但我找不到解决方案。这是我试过的:
使用ajax加载Popover:
$('.item-instances').popover({
trigger: 'click',
placement: 'bottom',
title: 'Title',
html: true,
content: function(){
var toReturn = [];
$.each(itemInstances($(this)), function(k, v){
toReturn[k] = '<a href="#" class="instance-image-'+ v.image_id +'">Abc</a>';
});
return toReturn;
}
});
这就是我试图从popover中触发链接的内容:
$( document ).ajaxComplete(function() {
$('a[class^="instance-image-"]').each(function(index, el) {
$(this).on('click', function(event) {
event.preventDefault();
console.log('test');
});
});
});
任何建议都应该是伟大的。谢谢。
答案 0 :(得分:2)
.parent().delegate()
之后链.popover()
,如下所示:
$('.item-instances').popover({
trigger: 'click',
placement: 'bottom',
title: 'Title',
html: true,
content: function() {
var toReturn = [];
// commented out for demo
//$.each(itemInstances($(this)), function(k, v){
//toReturn[k] = '<a href="#" class="instance-image-'+ v.image_id +'">Abc</a>';
//});
//return toReturn;
return '<a href="#" class="">Click ME</a>'
}
}).parent().delegate('a', 'click', function() {
event.preventDefault();
alert('test');
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<br>
<br>
<div class="bs-example">
<button id="my_awesome_element" type="button" class="btn btn-primary item-instances" data-toggle="popover" title="Popover title">Popover</button>
</div>
答案 1 :(得分:1)
您可能会多次绑定它,您可以使用unbind()
并执行以下操作:
$('.item-instances').popover({
trigger: 'click',
placement: 'bottom',
title: 'Title',
html: true,
content: function(){
var toReturn = [];
$('.item-instances').each(function(k, v){
toReturn[k] = '<a href="#" class="instance-image-'+ k +'">Abc</a>';
});
return toReturn;
}
});
function reBindListeners() {
$('a[class^="instance-image-"]').each(function(index, el) {
$(this).unbind().on('click', function(event) {
event.preventDefault();
console.log('test');
alert('works');
});
});
}
$( document ).ajaxComplete(reBindListeners);
// for example
$(document).on('shown.bs.popover', reBindListeners);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<button type="button" class="btn btn-default item-instances" data-container="body" data-toggle="popover">
Popover on bottom
</button>
注意我稍微修改了您的内容,因为我没有您的功能/数据。