使用Bootstrap 4,我有一个popover集来显示一些HTML内容。在popover中,我想使用jQuery显示/隐藏一个带有附加内容的div,但我无法让它显示隐藏的内容。
HTML
<div class="text-center">
<button id="show-popover" type="button" class="btn btn-primary mt-5" data-toggle="popover">Click Me</button>
</div>
<!-- popover content -->
<div id="popover-content" class="d-none">
<div class="card border-0">
<div class="card-body">
<a href="#" id="show-div">Show more content</a>
<div id="hidden-content" class="d-none">
div with more content...
</div>
</div>
</div>
</div>
jQuery
$(function () {
$('#show-popover').popover({
container: 'body',
html: true,
placement: 'bottom',
sanitize: false,
content: function() {
return $('#popover-content').html();
}
})
});
$('#show-div').click(function(){
$('#hidden-content').toggle();
});
链接到CodePen
当您动态地将内容(即:$('#popover-content').html()
(附加到popover时,您需要将单击处理程序绑定到某个静态元素,并使用class
选择器而不是id
来获取hidden-content
的引用,使用$(this).parent().find('.hidden-content').toggle();
来隐藏和显示。
演示代码 :
$(function() {
$('#show-popover').popover({
container: 'body',
html: true,
placement: 'bottom',
sanitize: false,
content: function() {
return $('#popover-content').html();
}
})
});
//call handler like below ..
$(document).on('click', '.card-body > #show-div', function() {
//then use .find to get the div and then show/hide
$(this).parent().find('.hidden-content').toggle();
});
.d-none {
display: none
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<div class="text-center">
<button id="show-popover" type="button" class="btn btn-primary mt-5" data-toggle="popover">Click Me</button>
</div>
<!-- popover content -->
<div id="popover-content" class="d-none">
<div class="card border-0">
<div class="card-body">
<a href="#" id="show-div">Show more content</a>
<div class="hidden-content d-none">
div with more content...
</div>
</div>
</div>
</div>