如何在 if with javascript 中使用 AND 语句?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12364798/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:49:39  来源:igfitidea点击:

How can use AND statement in if with javascript?

javascript

提问by Teodoris

Hello everyone I'm trying to run multiple javascripts and use AND statement. When user click an option which has value="1986" and click other option which has value="3", some text will appear. I have used AND statement in if statement but it doesn't work. Here is my code :

大家好,我正在尝试运行多个 javascript 并使用 AND 语句。当用户单击 value="1986" 的选项并单击 value="3" 的其他选项时,会出现一些文本。我在 if 语句中使用了 AND 语句,但它不起作用。这是我的代码:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script></script>
    <script type="text/javascript">
$(document).ready(function() {

    $('#main').on('change', '.select-box', function() {

        if ($(".select-box option[value='3']").attr('selected') & $(".select-box option[value='1986']").attr('selected')) {

            $('#demo').html("Hello World");

        }



    });

});
    </script>
<script type="text/javascript">

var x="",i;
for(i=1986;i<2013;i++)
{
x=x + "<option value='"+i+"'> " + i + "</option>";
}
$(document).ready(function() {
document.getElementById("demo2").innerHTML="<select class='select-box'>"+x+"</select>";
});
</script>


</head>
<body>  
    <p id="demo2"></p>
    <div id="main">
<select class="select-box">
      <option value="0">alert</option>
      <option value="1">alert to</option>
      <option value="2">no alert</option>
      <option value="3">best alert</option>
    </select> 
<p><br/>
    <div id="demo"></div>

    </div>


    </body>

回答by Mihai Iorga

You need to use &&

你需要使用 &&

if ($(".select-box option[value='3']").attr('selected') && $(".select-box option[value='1986']").attr('selected'))
________________________________________________________^

Logical operators:

逻辑运算符:

&& = and
|| = or
!  = not

and you must change the select class from first selectotherwise you will not get them both.

并且您必须首先更改选择类,select否则您将无法同时获得它们。

回答by aug

To use the AND statement, it should be &&.

要使用 AND 语句,它应该是&&.

So for your if statement it should be

所以对于你的 if 语句应该是

if ($(".select-box option[value='3']").attr('selected') && $(".select-box option[value='1986']").attr('selected')) {
            $('#demo').html("Hello World");
}

Hereis more information on boolean logic.

是有关布尔逻辑的更多信息。

回答by Thomas David Kehoe

The second (outer) parentheses seem to be important too.

第二个(外)括号似乎也很重要。