如何解决Bootstrap 4 开关在弹出窗口中不起作用
我试图在使用 Bootstrap 4 创建的 Popover 中包含一个开关。问题是该开关可以输出 popover 而不是内部。
示例
<html>
<head>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.min.js"></script>
</head>
<body>
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" id="chkPrv">
<label class="custom-control-label" for="chkPrv">Output Popover</label>
</div>
<button type="button" class="btn btn-lg btn-danger" data-toggle="popover">Click to toggle popover</button>
<div id="PopoverContent" class="d-none">
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" id="chkPal">
<label class="custom-control-label" for="chkPal">Input Popover</label>
</div>
</div>
<script>
$('[data-toggle="popover"]').popover(
{
html: true,sanitize: false,content: function () { return $("#PopoverContent").html(); }
});
</script>
</body>
</html>
解决方法
问题是 DOM 有两个带有 id="chkPal"
的元素:一个在隐藏的 div 中,另一个在你的 JS 运行后出现在 popover 内容中。有效的 HTML 要求元素具有唯一的 ID。
当你点击popover中的switch标签时,隐藏div中的switch就会被抛出,因为它首先出现在DOM中。
要解决此问题,请尝试使用 template
HTML tag。注意:它是 not fully supported by older Microsoft browsers。如果这是一个问题,您可以在 JS 中而不是 HTML 中编写内容。
查看下面的代码片段。
$('[data-toggle="popover"]').popover(
{
html: true,sanitize: false,content: function () { return $("#PopoverContent").html(); }
});
<html>
<head>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.min.js"></script>
</head>
<body>
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" id="chkPrv">
<label class="custom-control-label" for="chkPrv">Output Popover</label>
</div>
<button type="button" class="btn btn-lg btn-danger" data-toggle="popover" id="popoverSwitch">Click to toggle popover</button>
<template id="PopoverContent">
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" id="chkPal">
<label class="custom-control-label" for="chkPal">Input Popover</label>
</div>
</template>
</body>
</html>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。