<a href="" onclick=""> if function

时间:2017-03-05 09:39:19

标签: javascript jquery html

I don't really know how to approach this if statement. I want to open the side menu on click, and close it on click again. This is the code I have for opening and closing:

<script>

    /* Set the width of the side navigation to 250px */
function openNav() {
    document.getElementById("mySidenav").style.width = "250px";
}

/* Set the width of the side navigation to 0 */
function closeNav() {
    document.getElementById("mySidenav").style.width = "0";
}

</script>

I've tried using if statement, but I am not sure how to define "if a href is equal to open, then close".

This is a href:

<ul>
  <li><a href="#" id="up" onClick="openNav()" >Menu</a></li>
</ul>

I also tired to use toggle jQuery, but the link didn't react.

$(document).ready(function(){
    $("#up").click(function(){
        $("#mySidenav").toggle();
    });
});

Any help is appreciated.

5 个答案:

答案 0 :(得分:1)

这有效:

&#13;
&#13;
$(document).ready(function() {
      $("#up").click(function(e) {
            e.preventDefault();
            $("#mySidenav").toggle()
      });
});
&#13;
#mySideNav {
  overflow: hidden;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mySidenav">
  my side nav
</div>
<button id="up">toggle</button>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以像这样调用内联commit('loading/TOGGLE_LOADING', null, { root: true }) 函数:

javascript

答案 2 :(得分:0)

您好,我可以在您的jquery代码中看到一个小问题。 当您单击元素时,首先应使用删除默认值。 e.preventDefault()

代码变为

$(document).ready(function(){
    $("#up").click(function(e){
e.preventDefault();
        $("#mySidenav").toggle();

答案 3 :(得分:0)

而不是创建两个关闭和打开导航功能。您可以使用CSS切换类并处理显示/隐藏。 通过这种方式,您将提高页面性能并处理CSS中的所有内容,而不是JS中的内容。

&#13;
&#13;
var btn = document.querySelector('button');
var nav = document.querySelector('nav');

btn.addEventListener('click', toggleNav);

function toggleNav() {
  nav.classList.toggle('open');
}
&#13;
nav {
  background-color: steelblue;
  color: #fff;
  display: inline-block;
  padding: 5px;
  border-radius: 4px;
  transform: translateX(-1000%);
  transition: all 0.7s;
}

nav.open {
  transform: translateX(0);
}
&#13;
<nav>
  This is your nav
</nav>

<button>
Show/Hide Nav
</button>
&#13;
&#13;
&#13;

答案 4 :(得分:0)

在openNav中

,将绑定点击功能更改为closeNav。在closeNav中,将绑定点击功能更改为openNav。这意味着在Nav改变时保持绑定功能的改变