简体   繁体   中英

Javascript function with same name

I want o use function with same name in js, basically there is one link:

<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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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