单击事件在响应式菜单中不起作用

时间:2015-02-02 16:53:48

标签: javascript jquery html css twitter-bootstrap

当我在手机上测试我的菜单时,它会有响应式菜单,它会修改它会显示两个按钮,一个用于导航栏,另一个用于切换侧栏以删除隐藏类xs和hidden-sm。我的问题是btnToggleSidebar没有响应点击事件有人可以帮助我吗?

html nav

    <nav class="navbar navbar-default navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle collapsed pull-left" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar" style="color:#fff"></span>
                    <span class="icon-bar" style="color:#fff"></span>
                    <span class="icon-bar" style="color:#fff" ></span>
                </button>
                <button type="button" id="btnToggleSidebar" class="navbar-toggle pull-right" data-toggle="collapse" data-target=".navbar-ex2-collapse">
                    <span class="sr-only">Toggle navigation</span>
                    <i class="glyphicon glyphicon-cog" style="color:#fff"></i>
                </button>

                    <a class="navbar-brand" id="goHome" href="/Home/MyEvents"><span class="logo logo-icon"></span></a>
                    <a class="navbar-brand" id="goHome" href="/Home/MyEvents">@ViewBag.Configname</a>
</div>
            <div id="navbar" class="navbar-collapse collapse">
                @*<ul class="nav navbar-nav">
                    <li class="active"><a href="#">Home</a></li>
                    <li><a href="#about">About</a></li>
                    <li><a href="#contact">Contact</a></li>
                </ul>*@
                <ul class="nav navbar-nav navbar-right">
                    <li><a id="username" href="./">@ViewBag.UsernameAndRole <span class="sr-only ">(current)</span></a></li>
                </ul>
            </div><!--/.nav-collapse -->
        </div>
    </nav>

JavaScript

   $(document).on('click', 'button #btnToggleSidebar.navbar-toggle', function () {

        alert("defvs");
        $("div").toggleClass("hidden-sm").toggleClass("hidden-xs");

    });

3 个答案:

答案 0 :(得分:1)

删除button#btnToggleSidebar.navbar-toggle

之间的空格
 $(document).on('click', 'button#btnToggleSidebar.navbar-toggle', function () {

        alert("defvs");
        $("div").toggleClass("hidden-sm").toggleClass("hidden-xs");

    });

答案 1 :(得分:0)

不确定您选择的目标是什么,但将其更改为:

$(document).on('click', '#btnToggleSidebar', function () {
  alert("defvs");
  $("div").toggleClass("hidden-sm").toggleClass("hidden-xs");
});

引发警报。由于#btnToggleSidebar.navbar-toggle适用于同一元素,因此您只需定位ID并将点击功能应用于此。

请注意,此事件触发后您还有其他问题:在移动视图中,导航栏上的按钮会完全消失。

答案 2 :(得分:0)

试试这个

$('.pull-left').on('click', function () {

    alert("Hiding Nav");
    $('.navbar-nav:first-child').toggleClass("hidden-sm");


});
$('.pull-right').on('click', function () {

    alert("Hiding Sidebar");
      $('.nav:last-child').toggleClass("hidden-xs");

});