简体   繁体   English

如果用javascript怎么用AND语句?

[英]How can use AND statement in if with javascript?

Hello everyone I'm trying to run multiple javascripts and use AND statement. 大家好我正在尝试运行多个javascripts并使用AND语句。 When user click an option which has value="1986" and click other option which has value="3", some text will appear. 当用户单击值为“1986”的选项并单击其他值为“3”的选项时,将显示一些文本。 I have used AND statement in if statement but it doesn't work. 我在if语句中使用了AND语句,但它不起作用。 Here is my code : 这是我的代码:

<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>

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 select otherwise you will not get them both. 并且您必须从第一次select更改选择类,否则您将不会同时获得它们。

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");
}

Here is more information on boolean logic. 以下是有关布尔逻辑的更多信息。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM