从另一个文件加载的导航栏中的弹出窗口不起作用

Popover in Navbar loaded from another file does not work

我正在构建一个带有导航栏的网站,我从另一个 html 文件加载导航栏,如下所示:

导航栏HTML

<nav class="navbar fixed-top navbar-expand-lg bg-dark navbar-dark">
  <a class="navbar-brand" href="index.html">Site</a>
  <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
    <div class="navbar-nav">
    <a class="nav-item nav-link" href="about.html">About</a>
    <a class="nav-item nav-link" href="dashboard">Dashboard</a>
    <a class="nav-item nav-link" id="popover" href="#" )">Login</a>
    <div id="popover-content" class="d-none">
      <div class="form-inline">
        <input type="text" class="form-control" id="username" placeholder="Username" required>
      </div>
      <div class="form-inline">
        <input type="password" class="form-control" id="loginPassword" placeholder="Password" required>
      </div>
      <button type="submit" class="btn btn-primary" id="loginSubmit">Submit</button>
    </div>    
    <a class="nav-item nav-link" href="signup.html">Sign Up</a>
    </div>
  </div>
</nav>

这里是 jQuery 将其拉入页面:

$(function(){
   $("#nav-placeholder").load("navbar.html");
});

这工作正常,页面上加载了导航栏。但是在导航栏中(如果您在上面的代码中注意到)有一个弹出窗口,我想在用户单击“登录”按钮时使用它。

这里是 popover 代码:

$('a[rel=popover]').popover();
$("#popover").popover({
    html: true, 
    container: 'body',
    content: function() {
      return $("#popover-content").html();
    }
})

如果我在页面本身上有整个导航栏代码,这个弹出窗口就可以工作,但为了保持代码干净,我更喜欢从另一个文件加载导航栏。但是当这样做时,弹出窗口根本不起作用。我在控制台上也没有收到任何错误。什么都没有发生:(

有什么建议吗?

注意:要让导航栏从另一个 HTML 文件加载,我需要 运行 一个简单的 HTTPServer。这会导致问题吗?

谢谢!

Popover代码是在导航栏加载代码之前还是之后? Popover 脚本应该在导航栏加载脚本之后。

希望对您有所帮助。

在jQuery加载回调函数中初始化弹出窗口。

$(function(){
    $("#nav-placeholder").load("navbar.html",function(){
        $('a[rel=popover]').popover();
        $("#popover").popover({
            html: true, 
            container: 'body',
            content: function() {
            return $("#popover-content").html();
        }
        })
    });
});

Demo