简体   繁体   English

具有相同名称的Javascript函数

[英]Javascript function with same name

I want o use function with same name in js, basically there is one link: 我想在js中使用具有相同名称的函数,基本上有一个链接:

<a onClick="showjury1();" >show</a>

when the user is on desktop I want this code to be executed: 当用户在桌面上时,我希望执行以下代码:

if (window.screen.width >= 1150) {
  function showjury1() {
    document.getElementById("jury1").style.display = "block";
    document.getElementById("juryline1").style.display = "none";
  }
}

and when the user is on mobile or at any other resolution I want this code to be executed: 当用户使用移动设备或其他分辨率时,我希望执行以下代码:

if (window.screen.width <= 500) {
  function showjury1() {
    document.getElementById("jury1").style.display = "none";
    document.getElementById("juryline1").style.display = "block";
  }
}

Is this possible? 这可能吗? I have executed it and it gives errors; 我已经执行了它,它给出了错误; jury1 is not defined etc. 未定义jury1等。

Why do you need to define that function twice? 为什么需要两次定义该函数? Just use your conditional statement correctly 只要正确使用您的条件语句

function showjury1()
{
    if(window.screen.width >= 1150)
    {
         document.getElementById("jury1").style.display = "block";
         document.getElementById("juryline1").style.display = "none";
    }
    else if(window.screen.width <= 500)
    {
        document.getElementById("jury1").style.display = "none";
        document.getElementById("juryline1").style.display = "block";
    }
    else
    {
       // might want to do something here too
    }
}

You can also do something like: 您还可以执行以下操作:

if(window.screen.width >= 1150){
  window.showjury1 = function(){
    ...
  }
}else{
  window.showjury1 = function(){
    ...
  }
}    

You can put the condition into the function, then you don't need to define the same function twice, because that isn't possible the way you want it to be. 您可以将条件放入函数中,然后就不需要定义两次相同的函数,因为这不可能像您希望的那样进行。

function showjury1 {
if(window.screen.width >= 1150)
{
     document.getElementById("jury1").style.display = "block";
     document.getElementById("juryline1").style.display = "none";
}
else if(window.screen.width <= 500)
{
    document.getElementById("jury1").style.display = "none";
    document.getElementById("juryline1").style.display = "block";`
}
}

Instead of defining your showjury1 function inside your if statements, put your if statements inside your showjury1 function. 不用在if语句中定义showjury1函数,而是将if语句放入showjury1函数中。

showjury1(){
    if(check window width){...}
    else if(check different width){....}
}

and make sure your html is loaded before your Javascript otherwise you will get a undefined error when you try to click your button that calls your function. 并确保在加载Javascript之前先加载了html,否则当您尝试单击调用函数的按钮时,将会得到未定义的错误。

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

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