JQuery: more elegant if / else with selectors

I often repeat this type of code:

if ($(this).val() == 'X') { $('#something').show(); }
else                      { $('#something').hide(); }

I'm not crazy about the fact that $ ('# something') appears twice. Is there a more elegant way to express it?

[Update] I formulated the question poorly - I'm looking for a general solution, not just show / hide (and therefore switch). For the general case of taking different actions on the selected element (s) based on the conditional, is there a more elegant design?

+3
source share
2 answers

for the general question that "#something" appears twice, I would say it is more readable to have it twice. otherwise, you complete the following:

$('#something')[$(this).val()=='X'?'show':'hide']();
+3
source

toggle()

(true , ).

true, toggle ( ). false, ( show method).

var result = ($(this).val() != 'X');
$('#something').toggle(result);

$('#something').toggle('X' != $(this).val());
+8

Source: https://habr.com/ru/post/1708206/


All Articles