简体   繁体   中英

Unite in one conditional statements IF different conditional statements IF (javaScript)

  var message;    
        if ( $('#one').length == 1 ){
           message = "101";
        }
        if ( $('#two').length == 2 ){ 
           message = "102";
        }
        if ( $('#third').length == 3 ){
           message = "103";
        }
    console.log(message);

How I can do unite all IF in one IF use operator ( || or another) and depending on the condition show different message? I tried do it but was unfortunate. Thank you for your advance.

Actually you can simply do

var message = "10"+$('#one').length;
console.log(message);

note that have aa condition for 0 length. However why you have multiple elements with same id? you mean class ?

The resulting .length of using selector "#one" should always be either 0 or 1 as id of element in document should be unique, not duplicated at another element.

If there are multiple elements having id "one" substitute class for id at the elements at HTML and use selector ".one" .

The question has changed, and to be honest is making less sense than before.

What I'll do is assume that you want to select all three elements, and configure a message based on how many actual elements were found. I'll use my second example from below to show how with IDs, though classes are nicer.

var msgs = {
  1: "101",
  2: "102",
  3: "103",
}

var message = msgs[$("#one,#two,#three").length] || "Unknown";

So now it will try to select all three, and will give a message based on how many were actually found.

This again does not assume that the actual situation is as simple as merely appending the length to a string.


original answer

I'm not going to make the assumption that there's always going to be such a neat paring between the .length and the message.

So a more general solution would be to use a switch statement.

var message;    
switch ( $('#one').length ) {
  case 1: message = "101"; break;
  case 2: message = "102"; break;
  case 3: message = "103"; break;
  default: message = "Unknown";
}
console.log(message);

A switch is not the only way. You could also create an object that associates a number with a message.

var msgs = {
  1: "101",
  2: "102",
  3: "103",
}

var message = msgs[$("#one").length] || "Unknown";

Note that jQuery will only return one element for an ID selector, though querySelectorAll could return multiple, though duplicate IDs isn't good.

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