简体   繁体   中英

if condition is true or skip all else conditions

xyz.html

<p id = x ngClick = close($event)></p>
<p id = y ngClick = close($event)></p>
<p id = z ngClick = close($event)></p>
<h1 id = a ngClick = close()></h1>

xyz.js

function close(event)
if (event.target.id === x){
....
}else if(event.target.id === y){
....
}else if(event.target.id === z){
.....
}

This function is to close current window and check for the event but when I'm not passing this event in other close methods(h1 tag) I'm getting the event is undefined error.

The error is correct. You need first check if event is defined, because you can't directly access target property if event is undefined.

function close(event)
   if(event){
    if (event.target.id === x){
    ....
    }else if(event.target.id === y){
    ....
    }else if(event.target.id === z){
    .....
    }
    }else{
           //H1 click condition
      }
}
 function close(event){
     if(event===undefined){

     //H1 got clicked
       return;
     }

     if (event.target.id === x){
     ....
     }else if(event.target.id === y){
     ....
     }else if(event.target.id === z){
     .....
     }
   }

Try this:

$scope.close = function(event) {
  if (!event) return;

  switch (event.target.id) {
    case "x":
      ...
      break;
    case "y":
      ...
      break;
    case "z":
      ...
      break;
    default:
      ...
      break;
  }
}

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