Вопрос

I am trying to improve my coding skills, but I can not seem to figure this out. How do I write the following in shorthand?

/* fade */
$('.toggle-ui').on({
    'click': function (e) {
        e.preventDefault();
        var divToFade = ['#logo', '#hide-interface'];

        $.each(divToFade, function(intValue, currentElement) {
            // check alpha state and switch
            var currOp = $(currentElement).css('opacity');

            if (currOp == 1) $(currentElement).css('opacity', 0.5);
            if (currOp == 0.5) $(currentElement).css('opacity', 1);
        });
    }
Это было полезно?

Решение

Use the ternary operator:

$(currentElement).css('opacity', currOp == 1 ? 0.5 : 1);

As a side note: I am used to using === over == to avoid accidental mistakes by unintended type coercion. To use it here, I would parse currOp to a number via +:

$(currentElement).css('opacity', +currOp === 1 ? 0.5 : 1);

For more information, have a look here.

Другие советы

You can also do simple math:

$(currentElement).css('opacity', 1.5 - currOp);

Since

1.5 - 1.0 = 0.5
1.5 - 0.5 = 1.0
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top