[英]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? 如何将所有IF合并到一个IF使用运算符(||或另一个)中,并根据条件显示不同的消息? 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. 请注意,条件为
0
长度。 However why you have multiple elements with same id? 但是,为什么有多个具有相同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. 使用选择器
"#one"
的结果.length
应该始终为0
或1
因为document
中元素的id
应该是唯一的,不能在另一个元素上重复。
If there are multiple elements having id
"one"
substitute class
for id
at the elements at HTML and use selector ".one"
. 如果有多个具有
id
"one"
的元素,请在HTML的元素处用id
替换class
,并使用选择器".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.
我将使用下面的第二个示例来说明如何使用ID,尽管类更好。
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. 我不会假设
.length
和消息之间总是存在如此巧妙的.length
。
So a more general solution would be to use a switch
statement. 因此,更通用的解决方案是使用
switch
语句。
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. switch
不是唯一的方法。 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. 请注意,尽管重复的ID不好,但jQuery只返回一个ID选择器元素,尽管
querySelectorAll
可以返回多个元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.