简体   繁体   English

javascript条件语句

[英]javascript conditional statements

I have a side navigation that, upon clicking a link, will do a certain function: 我有一个侧面导航,单击链接后将执行某些功能:

$(".side-nav ul li a").click(function(event) {
  $(".side-nav").stop().animate({"margin-top": "0px"}, 450);
});

I also have this same function trigger if the page loading has a hashtag 如果页面加载中有井号标签,我也有相同的函数触发器

if(window.location.hash) {
  $(".side-nav").stop().animate({"margin-top": "0px"}, 450);
}

What I am looking for is a way to combine the two to reduce redundancy. 我正在寻找一种将两者结合以减少冗余的方法。

If the url has a hashtag, trigger the function, else only trigger the function if a sidenav item is clicked. 如果url中有#标签,则触发该函数,否则,仅当单击sidenav项时才触发该函数。

I can't seem to wrap my head around this. 我似乎无法解决这个问题。 Any help would be much appreciated. 任何帮助将非常感激。

Thank you. 谢谢。

Put the code in a function and invoke it in both places. 将代码放在函数中,然后在两个地方调用它。

function sideNav() {
    $(".side-nav").stop().animate({"margin-top": "0px"}, 450);
}

$(".side-nav ul li a").click(function(event) {
    sideNav();
});

if(window.location.hash) {
    sideNav();
}

And your click handler can actually be rewritten like this if there's no other code to run: 如果没有其他代码可以运行,那么您的click处理程序实际上可以像这样重写:

$(".side-nav ul li a").click(sideNav);

If there are any arguments that need to be passed to sideNav , then this rewrite won't be suitable. 如果有任何参数需要传递给sideNav ,则此重写将不合适。 They would need to be manually passed from within a click handler that invokes the function. 需要从调用该函数的点击处理程序中手动传递它们。

var animateSideNav = function() {
  $(".side-nav").stop().animate({"margin-top": "0px"}, 450);
}

$(".side-nav ul li a").click(animateSideNav);

if(window.location.hash) {
  animateSideNav();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM