false statement not executed by ternary operator

时间:2016-04-21 21:48:42

标签: javascript php web twig

In the following code, the ternary operator isn't assigning the value if condition returns false!

<script>
                function lgn() {
                    document.getElementById('overlay').style.display = 'none' ? 'block':'none';
                    document.getElementById('lgn').style.display = 'none' ? 'block':'none';
                }
</script>

I am actually trying to make a overlay over my webpage, following is the Twig:

<div class="nvg">
                <ul>
                    {% block links %}
                    <li class="n.link"><span class="fa fa-times close" onclick="lgn()"></span></li>
                    {% endblock %}
                </ul>
</div>

AND

{% block overlay %}
        {{ form_start(form, {'attr':{'id':'lgn'}}) }}
        <span class="fa fa-times close" onclick="lgn()"></span><br />
        <span>Login:</span>
        {{ form_widget(form.email, {'attr':{'placeholder':'email'}}) }}
        {{ form_widget(form.pass, {'attr':{'placeholder':'password','class':'pass'}}) }}
        {{ form_end(form) }}
{% endblock %}

Please help...

3 个答案:

答案 0 :(得分:3)

The ternary makes a boolean decisions, and you've written yours to always evaluate to true:

'none' ? 'block':'none';

is basically the same as

if ('none' is true) { 
   'block'
} else {
   'none';
}

Since none as a string is a truthy (evaluates to the same as boolean true in most cases), you always pick the "true" path in the ternary.

答案 1 :(得分:1)

Your ternary doesn't make sense.

document.getElementById('overlay').style.display = 'none' ? 'block':'none';

There's no logical evaluation to make, and the string will (mostly) always be evaluated to true. Do something like this:

document.getElementById('overlay').style.display = (document.getElementById('overlay').style.display == 'none') ? 'block' : 'none';

Your best solution (in terms of cleanliness) is to make the selectors into variables.

function lgn() {
    element1 = document.getElementById('overlay');
    element1.style.display = (element1.style.display == 'none') ? 'block' : 'none';

    element2 = document.getElementById('lgn');
    element2.style.display = (element2.style.display == 'none') ? 'block' : 'none';
}

答案 2 :(得分:1)

You always assign the display to 'block' because the 'none' is a non-empty string and it is always true

document.getElementById('overlay').style.display = 'none' ? 'block':'none';

Use this statement

var display = document.getElementById('overlay').style.display
document.getElementById('overlay').style.display = display == 'none' ? 'block':'none';