如何在单个函数中定义多个任务并在javascript中使用

时间:2015-10-19 11:14:08

标签: javascript html html5

<div id="demo" onclick="tasks("fade")">
   <div id="demo" onclick="tasks("glow")">
    <div id="demo" onclick="tasks("slide")">
       <script>
       function tasks(){
           fade = do fade;
           glow =  make glows;
           slide = move slide; 
       }
       </script>

如何使用单个函数并声明多个任务并使用它们,就像我在上面创建的那样?

2 个答案:

答案 0 :(得分:2)

您可以使用函数中可用的变量:

<script>
 function tasks(effect){
 switch(effect){
  case "fade":
    // execute some code here;
    break;
  case "glow":
    // execute some code here;
    break;
  case "slide":
    // execute some code here;
    break;
}
   }
 </script>

答案 1 :(得分:1)

你可以这样做,虽然它可以通过许多其他方式完成。

function tasks(action){
 if(action === "fade"){
   console.log("Handle fade action here");
 }
 else if(action === "glow"){
    console.log("Handle glow action here");
 }
 else if(action === "slide"){
   console.log("Handle slide action here");
 }
}
<div id="demo" onclick="tasks('fade')">fade</div>
 <div id="demo" onclick="tasks('glow')">glow</div>
<div id="demo" onclick="tasks('slide')">slide</div>

使用switch

function tasks(action){
  switch(action){
  
     case "fade": console.log("Fade action here");
                  break;
      
     case "glow": console.log("Glow action here");
                  break;
      
     case "slide": console.log("Slide action here");
                  break; 
      
     
     default :console.log("any other actions here")
  
  
  }
  
}
<div id="demo" onclick="tasks('fade')">Fade</div>
 <div id="demo" onclick="tasks('glow')">Glow</div>
<div id="demo" onclick="tasks('slide')">Slide</div>
<div id="demo" onclick="tasks('any other')">any other</div>